PHP.SU

Программирование на PHP, MySQL и другие веб-технологии
PHP.SU Портал     На главную страницу форума Главная     Помощь Помощь     Поиск Поиск     Поиск Яндекс Поиск Яндекс     Вакансии  Пользователи Пользователи

Страниц (5): « 1 2 [3] 4 5 »

> Найдено сообщений: 63
lraido Отправлено: 19 Декабря, 2011 - 14:38:40 • Тема: Social Engine • Форум: CMS и фреймворки

Ответов: 4
Просмотров: 1644
Добрый день!

Засел изучать social engine.

Поможете разобраться что к чему? Знаю РНР, но очень много неясностей.

Например, как из кода подключаться к базам данных. Ни одной функции не увидел!
lraido Отправлено: 09 Ноября, 2011 - 19:26:17 • Тема: jQuery Feature Carousel Plugin - aльтернатива • Форум: JavaScript & VBScript

Ответов: 1
Просмотров: 2384
Здравствуйте.

Есть такая галерея:

http://rujoomla[dot]ru/index.php?opt[dot][dot][dot]ted&Itemid=5

http://www[dot]w3avenue[dot]com/2010/04/[dot][dot][dot]carousel-plugin/

которая делает карусель изображениям.

К сожалению ознакомившись с кодом я понял, что карусель построена на трех позициях(выводимых картинках), и например увеличить количество позиций для красоты, но это проблематично.

Есть ли альтернатива такой карусели, или может возможно изменить код?



Помогите пожалуйста. Очень нужно.



Главный код.

CODE (javascript):
скопировать код в буфер обмена
  1.  
  2.  
  3. /*!
  4.  * Feature Carousel, Version 1.0
  5.  * http://www.bkosolutions.com
  6.  *
  7.  * Copyright 2010 Brian Osborne
  8.  * Licensed under GPL version 3
  9.  *
  10.  * http://www.gnu.org/licenses/gpl.txt
  11.  */
  12. (function($) {
  13.  
  14.     $.fn.featureCarousel = function (options) {
  15.  
  16.         // override the default options with user defined options
  17.         options = $.extend({}, $.fn.featureCarousel.defaults, options || {});
  18.  
  19.         return $(this).each(function () {
  20.  
  21.             /* These are univeral values that are used throughout the plugin. Do not modify them
  22.              * unless you know what you're doing. Most of them feed off the options
  23.              * so most customization can be achieved by modifying the options values */
  24.             var pluginData = {
  25.                 currentCenterNum:       options.startingFeature,
  26.                 containerWidth:         0,
  27.                 containerHeight:        0,
  28.                 largeFeatureWidth:      0,
  29.                 largeFeatureHeight:     0,
  30.                 smallFeatureWidth:      0,
  31.                 smallFeatureHeight:     0,
  32.                 totalFeatureCount:      $(this).children("div").length,
  33.                 currentlyMoving:        false,
  34.                 featuresContainer:      $(this),
  35.                 featuresArray:          [],
  36.                 containerIDTag:         "#"+$(this).attr("id"),
  37.                 timeoutVar:             null,
  38.                 rotationsRemaining:     0,
  39.                 itemsToAnimate:         0,
  40.                 borderWidth:                    0
  41.             };
  42.  
  43.                 setupFeatureDimensions();
  44.                 setupCarousel();
  45.                 setupFeaturePositions();
  46.                 setupBlips();
  47.                 initiateMove(true,1);
  48.  
  49.             /**
  50.              * Function to preload the images in the carousel if desired.
  51.              * This is not recommended if there are a lot of images in the carousel because
  52.              * it may take a while. Functionality does not depend on preloading the images
  53.              */
  54.             function preload(callback) {
  55.                 // user may not want to preload images
  56.                 if (options.preload == true) {
  57.                     var $imageElements = pluginData.featuresContainer.find("img");
  58.                     var loadedImages = 0;
  59.                     var totalImages = $imageElements.length;
  60.  
  61.                     $imageElements.each(function () {
  62.                         // Attempt to load the images
  63.                         $(this).load(function () {
  64.                             // Add to number of images loaded and see if they are all done yet
  65.                             loadedImages++;
  66.                             if (loadedImages == totalImages) {
  67.                                 // All done, perform callback
  68.                                 callback();
  69.                             }
  70.                         });
  71.                         // The images may already be cached in the browser, in which case they
  72.                         // would have a 'true' complete value and the load callback would never be
  73.                         // fired. This will fire it manually.
  74.                         if (this.complete) {
  75.                             $(this).trigger('load');
  76.                         }
  77.                     });
  78.                 } else {
  79.                     // if user doesn't want preloader, then just go right to callback
  80.                     callback();
  81.                 }
  82.             }
  83.  
  84.             // Gets the feature container based on the number
  85.             function getContainer(featureNum) {
  86.                 return pluginData.featuresArray[featureNum-1];
  87.             }
  88.  
  89.             // get a feature given it's set position (the position that doesn't change)
  90.             function getBySetPos(position) {
  91.                 $.each(pluginData.featuresArray, function () {
  92.                     if ($(this).data().setPosition == position)
  93.                         return $(this);
  94.                 });
  95.             }
  96.  
  97.             // get previous feature number
  98.             function getPreviousNum(num) {
  99.                 if ((num - 1) == 0) {
  100.                     return pluginData.totalFeatureCount;
  101.                 } else {
  102.                     return num - 1;
  103.                 }
  104.             }
  105.  
  106.             // get next feature number
  107.             function getNextNum(num) {
  108.                 if ((num + 1) > pluginData.totalFeatureCount) {
  109.                     return 1;
  110.                 } else {
  111.                     return num + 1;
  112.                 }
  113.             }
  114.  
  115.             /**
  116.              * Because there are several options the user can set for the width and height
  117.              * of the feature images, this function is used to determine which options were set
  118.              * and to set the appropriate dimensions used for a small and large feature
  119.              */
  120.             function setupFeatureDimensions() {
  121.                 // Set the height and width of the entire carousel container
  122.                 pluginData.containerWidth = pluginData.featuresContainer.outerWidth();
  123.                 pluginData.containerHeight = pluginData.featuresContainer.outerHeight();
  124.  
  125.                 // Grab the first image for reference
  126.                 var $firstFeatureImage = $(pluginData.containerIDTag).find("div img:first");
  127.  
  128.                 // Large Feature Width
  129.                 if (options.largeFeatureWidth > 1)
  130.                     pluginData.largeFeatureWidth = options.largeFeatureWidth;
  131.                 else if (options.largeFeatureWidth > 0 && options.largeFeatureWidth < 1)
  132.                     pluginData.largeFeatureWidth = $firstFeatureImage.width() * options.largeFeatureWidth;
  133.                 else
  134.                     pluginData.largeFeatureWidth = $firstFeatureImage.outerWidth();
  135.                 // Large Feature Height
  136.                 if (options.largeFeatureHeight > 1)
  137.                     pluginData.largeFeatureHeight = options.largeFeatureHeight;
  138.                 else if (options.largeFeatureHeight > 0 && options.largeFeatureHeight < 1)
  139.                     pluginData.largeFeatureHeight = $firstFeatureImage.height() * options.largeFeatureHeight;
  140.                 else
  141.                     pluginData.largeFeatureHeight = $firstFeatureImage.outerHeight();
  142.                 // Small Feature Width
  143.                 if (options.smallFeatureWidth > 1)
  144.                     pluginData.smallFeatureWidth = options.smallFeatureWidth;
  145.                 else if (options.smallFeatureWidth > 0 && options.smallFeatureWidth < 1)
  146.                     pluginData.smallFeatureWidth = $firstFeatureImage.width() * options.smallFeatureWidth;
  147.                 else
  148.                     pluginData.smallFeatureWidth = $firstFeatureImage.outerWidth() / 2;
  149.                 // Small Feature Height
  150.                 if (options.smallFeatureHeight > 1)
  151.                     pluginData.smallFeatureHeight = options.smallFeatureHeight;
  152.                 else if (options.smallFeatureHeight > 0 && options.smallFeatureHeight < 1)
  153.                     pluginData.smallFeatureHeight = $firstFeatureImage.height() * options.smallFeatureHeight;
  154.                 else
  155.                     pluginData.smallFeatureHeight = $firstFeatureImage.outerHeight() / 2;
  156.             }
  157.  
  158.             /**
  159.              * Function to take care of setting up various aspects of the carousel,
  160.              * most importantly the default positions for the features
  161.              */
  162.             function setupCarousel() {
  163.                 // Set the total feature count to the amount the user wanted to cutoff
  164.                 if (options.displayCutoff > 0 && options.displayCutoff < pluginData.totalFeatureCount) {
  165.                     pluginData.totalFeatureCount = options.displayCutoff;
  166.                 }
  167.  
  168.                 // fill in the features array
  169.                 pluginData.featuresContainer.children("div").each(function (index) {
  170.                     if (index < pluginData.totalFeatureCount) {
  171.                         pluginData.featuresArray[index] = $(this);
  172.                     }
  173.                 });
  174.  
  175.                 // Determine the total border width around the feature if there is one
  176.                 if (pluginData.featuresContainer.children("div").first().css("borderLeftWidth") != "medium") {
  177.                     pluginData.borderWidth = parseInt(pluginData.featuresContainer.children("div").first().css("borderLeftWidth"))*2;
  178.                 }
  179.  
  180.                 // Place all the features in a center hidden position to start off
  181.                 pluginData.featuresContainer
  182.                     // Have to make the container relative positioning
  183.                     .children("div").each(function () {
  184.                         // Center all the features in the middle and hide them
  185.                         $(this).css({
  186.                             'left': (pluginData.containerWidth / 2) - (pluginData.smallFeatureWidth / 2) - (pluginData.borderWidth / 2),
  187.                             'width': pluginData.smallFeatureWidth,
  188.                             'height': pluginData.smallFeatureHeight,
  189.                             'top': options.smallFeatureOffset + options.topPadding,
  190.                             'opacity': 0
  191.                         });
  192.                     })
  193.                     // Set all the images to small feature size
  194.                     .find("img:first").css({
  195.                         'width': pluginData.smallFeatureWidth
  196.                     });
  197.  
  198.                 // figure out number of items that will rotate each time
  199.                 if (pluginData.totalFeatureCount < 4) {
  200.                     pluginData.itemsToAnimate = pluginData.totalFeatureCount;
  201.                 } else {
  202.                     pluginData.itemsToAnimate = 4;
  203.                 }
  204.  
  205.                 // Hide story info and set the proper positioning
  206.                 pluginData.featuresContainer.find("div > div")
  207.                     .hide();
  208.             }
  209.  
  210.             /**
  211.              * Here all the position data is set for the features.
  212.              * This is an important part of the carousel to keep track of where
  213.              * each feature within the carousel is
  214.              */
  215.             function setupFeaturePositions() {
  216.                 // give all features a set number that won't change so they remember their
  217.                 // original order
  218.                 $.each(pluginData.featuresArray, function (i) {
  219.                     $(this).data('setPosition',i+1);
  220.                 });
  221.  
  222.                 // Go back one - This is done because we call the move function right away, which
  223.                 // shifts everything to the right. So we set the current center back one, so that
  224.                 // it displays in the center when that happens
  225.                 var oneBeforeStarting = getPreviousNum(options.startingFeature);
  226.                 pluginData.currentCenterNum = oneBeforeStarting;
  227.  
  228.                 // Center feature will be position 1
  229.                 var $centerFeature = getContainer(oneBeforeStarting);
  230.                 $centerFeature.data('position',1);
  231.  
  232.                 // Everything before that center feature...
  233.                 var $prevFeatures = $centerFeature.prevAll();
  234.                 $prevFeatures.each(function (i) {
  235.                     $(this).data('position',(pluginData.totalFeatureCount - i));
  236.                 });
  237.  
  238.                 // And everything after that center feature...
  239.                 var $nextFeatures = $centerFeature.nextAll();
  240.                 $nextFeatures.each(function (i) {
  241.                     if ($(this).data('setPosition') != undefined) {
  242.                         $(this).data('position',(i + 2));
  243.                     }
  244.                 });
  245.  
  246.                 // if the counter style is for including number tags in description...
  247.                 if (options.counterStyle == 3) {
  248.                     $.each(pluginData.featuresArray, function () {
  249.                         var pos = getPreviousNum($(this).data('position'));
  250.                         var $numberTag = $("<span></span>");
  251.                         $numberTag.addClass("numberTag");
  252.                         $numberTag.html("("+ pos + " of " + pluginData.totalFeatureCount + ") ");
  253.                         $(this).find('div p').prepend($numberTag);
  254.                     });
  255.                 }
  256.             }
  257.  
  258.             /**
  259.              * The blips are built using this function. The position and look
  260.              * of the blips are completely determined by the CSS file
  261.              */
  262.             function setupBlips()
  263.             {
  264.                 // Only setup the blips if the counter style is 1 or 2
  265.                 if (options.counterStyle == 1 || options.counterStyle == 2) {
  266.                     // construct the blip list
  267.                     var $list = $("<ul></ul>");
  268.                     $list.addClass("blipsContainer");
  269.                     for (var i = 0; i < pluginData.totalFeatureCount; i++) {
  270.                         // Counter style 1 has no numbers, while 2 does
  271.                         var counter;
  272.                         if (options.counterStyle == 2)
  273.                             counter = "";
  274.                         else
  275.                             counter = i+1;
  276.  
  277.                         // Build the DOM for the blip list
  278.                         var $blip = $("<div>"+counter+"</div>");
  279.                         $blip.addClass("blip");
  280.                         $blip.css("cursor","pointer");
  281.                         $blip.attr("id","blip_"+(i+1));
  282.                         var $listEntry = $("<li></li>");
  283.                         $listEntry.append($blip);
  284.                         $listEntry.css("float","left");
  285.                         $listEntry.css("list-style-type","none");
  286.                         $list.append($listEntry);
  287.                     }
  288.                     // add the blip list and then make sure it's visible
  289.                     $(pluginData.containerIDTag).append($list);
  290.                     $list.hide().show();
  291.                 }
  292.             }
  293.  
  294.             // Move the highlighted blip to the currently centered feature
  295.             function changeBlip(oldCenter, newCenter)
  296.             {
  297.                 // get selectors for the two blips
  298.                 var $blipsContainer = pluginData.featuresContainer.find(".blipsContainer");
  299.                 var $oldCenter = $blipsContainer.find("#blip_"+oldCenter);
  300.                 var $newCenter = $blipsContainer.find("#blip_"+newCenter);
  301.  
  302.                 // change classes
  303.                 $oldCenter.removeClass("blipSelected");
  304.                 $newCenter.addClass("blipSelected");
  305.             }
  306.  
  307.             /**
  308.              * This function will set the autoplay for the carousel to
  309.              * automatically rotate it given the time in the options
  310.              */
  311.             function autoPlay() {
  312.                 // clear the timeout var if it exists
  313.                 if (pluginData.timeoutVar != null) {
  314.                     pluginData.timeoutVar = clearTimeout(pluginData.timeoutVar);
  315.                 }
  316.  
  317.                 // set interval for moving if autoplay is set
  318.                 if (options.autoPlay != 0) {
  319.                     var autoTime = (Math.abs(options.autoPlay) < options.carouselSpeed) ? options.carouselSpeed : Math.abs(options.autoPlay);
  320.                     pluginData.timeoutVar = setTimeout(function () {
  321.                         if (options.autoPlay > 0)
  322.                             initiateMove(true,1);
  323.                         else if (options.autoPlay < 0)
  324.                             initiateMove(false,1);
  325.                     }, autoTime);
  326.                 }
  327.             }
  328.  
  329.             // This is a helper function for the animateFeature function that
  330.             // will update the positions of all the features based on the direction
  331.             function rotatePositions(direction) {
  332.                 $.each(pluginData.featuresArray, function () {
  333.                     var newPos;
  334.                     if (direction == false) {
  335.                         newPos = getNextNum($(this).data().position);
  336.                     } else {
  337.                         newPos = getPreviousNum($(this).data().position);
  338.                     }
  339.                     $(this).data('position',newPos);
  340.                 });
  341.             }
  342.  
  343.             /**
  344.              * This function is used to animate the given feature to the given
  345.              * location. Valid locations are "left", "right", "center", "hidden"
  346.              */
  347.             function animateFeature($feature, direction)
  348.             {
  349.                 var new_width, new_height, new_top, new_left, new_zindex, new_padding, new_fade;
  350.  
  351.                 // Determine the old and new positions of the feature
  352.                 var oldPosition = $feature.data('position');
  353.                 var newPosition;
  354.                 if (direction == true)
  355.                     newPosition = getPreviousNum(oldPosition);
  356.                 else
  357.                     newPosition = getNextNum(oldPosition);
  358.  
  359.                 // Caculate new new css values depending on where the feature will be located
  360.                 if (newPosition == 1) {
  361.                     new_width = pluginData.largeFeatureWidth;
  362.                     new_height = pluginData.largeFeatureHeight;
  363.                     new_top = options.topPadding;
  364.                     new_zindex = $feature.css("z-index");
  365.                     new_left = (pluginData.containerWidth / 2) - (pluginData.largeFeatureWidth / 2) - (pluginData.borderWidth / 2);
  366.                     new_fade = 1.0;
  367.                 } else {
  368.                     new_width = pluginData.smallFeatureWidth;
  369.                     new_height = pluginData.smallFeatureHeight;
  370.                     new_top = options.smallFeatureOffset + options.topPadding;
  371.                     new_zindex = 1;
  372.                     new_fade = 0.4;
  373.                     // some info is different for the left, right, and hidden positions
  374.                     // left
  375.                     if (newPosition == pluginData.totalFeatureCount) {
  376.                         new_left = options.sidePadding;
  377.                     // right
  378.                     } else if (newPosition == 2) {
  379.                         new_left = pluginData.containerWidth - pluginData.smallFeatureWidth - options.sidePadding - pluginData.borderWidth;
  380.                     // hidden
  381.                     } else {
  382.                         new_left = (pluginData.containerWidth / 2) - (pluginData.smallFeatureWidth / 2) - (pluginData.borderWidth / 2);
  383.                         new_fade = 0;
  384.                     }
  385.                 }
  386.                 // This code block takes care of hiding the feature information if the feature is
  387.                 // NO LONGER going to be in the center
  388.                 if (newPosition != 1) {
  389.                     // Slide up the story information
  390.                     $feature.find("div")
  391.                         .hide();
  392.                 }
  393.  
  394.                 // Animate the feature div to its new location
  395.                 $feature
  396.                     .animate(
  397.                         {
  398.                             width: new_width,
  399.                             height: new_height,
  400.                             top: new_top,
  401.                             left: new_left,
  402.                             opacity: new_fade
  403.                         },
  404.                         options.carouselSpeed,
  405.                         options.animationEasing,
  406.                         function () {
  407.                             // Take feature info out of hiding if new position is center
  408.                             if (newPosition == 1) {
  409.                                 // fade in the feature information
  410.                                 $feature.find("div")
  411.                                     .fadeTo("fast",0.85);
  412.                             }
  413.                             // decrement the animation queue
  414.                             pluginData.rotationsRemaining = pluginData.rotationsRemaining - 1;
  415.                             // have to change the z-index after the animation is done
  416.                             $feature.css("z-index", new_zindex);
  417.                             // change blips if using them
  418.                             if (options.counterStyle == 1 || options.counterStyle == 2) {
  419.                                 if (newPosition == 1) {
  420.                                     // figure out what item was just in the center, and what item is now in the center
  421.                                     var newCenterItemNum = pluginData.featuresContainer.children("div").index($feature) + 1;
  422.                                     var oldCenterItemNum;
  423.                                     if (direction == false)
  424.                                         oldCenterItemNum = getNextNum(newCenterItemNum);
  425.                                     else
  426.                                         oldCenterItemNum = getPreviousNum(newCenterItemNum);
  427.                                     // now change the active blip
  428.                                     changeBlip(oldCenterItemNum, newCenterItemNum);
  429.                                 }
  430.                             }
  431.  
  432.                             // did all the the animations finish yet?
  433.                             var divide = pluginData.rotationsRemaining / pluginData.itemsToAnimate;
  434.                             if (divide % 1 == 0) {
  435.                                 // if so, set moving to false...
  436.                                 pluginData.currentlyMoving = false;
  437.                                 // change positions for all items...
  438.                                 rotatePositions(direction);
  439.  
  440.                                 // and move carousel again if queue is not empty
  441.                                 if (pluginData.rotationsRemaining > 0)
  442.                                     move(direction);
  443.                             }
  444.  
  445.                             // call autoplay again
  446.                             autoPlay();
  447.                         }
  448.                     )
  449.                     // select the image within the feature
  450.                     .find("img:first")
  451.                         // animate its size down
  452.                         .animate({
  453.                             width: new_width,
  454.                             height: new_height
  455.                         },
  456.                         options.carouselSpeed,
  457.                         options.animationEasing)
  458.                     .end();
  459.             }
  460.  
  461.             /**
  462.              * move the carousel to the left or to the right. The features that
  463.              * will move into the four positions are calculated and then animated
  464.              * rotate to the RIGHT when direction is TRUE and
  465.              * rotate to the LEFT when direction is FALSE
  466.              */
  467.             function move(direction)
  468.             {
  469.                 // Set the carousel to currently moving
  470.                 pluginData.currentlyMoving = true;
  471.  
  472.                 // Obtain the new feature positions based on the direction that the carousel is moving
  473.                 var $newCenter, $newLeft, $newRight, $newHidden;
  474.                 if (direction == true) {
  475.                     // Shift features to the left
  476.                     $newCenter = getContainer(getNextNum(pluginData.currentCenterNum));
  477.                     $newLeft = getContainer(pluginData.currentCenterNum);
  478.                     $newRight = getContainer(getNextNum(getNextNum(pluginData.currentCenterNum)));
  479.                     $newHidden = getContainer(getPreviousNum(pluginData.currentCenterNum));
  480.                     pluginData.currentCenterNum = getNextNum(pluginData.currentCenterNum);
  481.                 } else {
  482.                     $newCenter = getContainer(getPreviousNum(pluginData.currentCenterNum));
  483.                     $newLeft = getContainer(getPreviousNum(getPreviousNum(pluginData.currentCenterNum)));
  484.                     $newRight = getContainer(pluginData.currentCenterNum);
  485.                     $newHidden = getContainer(getNextNum(pluginData.currentCenterNum));
  486.                     pluginData.currentCenterNum = getPreviousNum(pluginData.currentCenterNum);
  487.                 }
  488.  
  489.                 // The z-index must be set before animations take place for certain movements
  490.                 // this makes the animations look nicer
  491.                 if (direction) {
  492.                     $newLeft.css("z-index", 3);
  493.                 } else {
  494.                     $newRight.css("z-index", 3);
  495.                 }
  496.                 $newCenter.css("z-index", 4);
  497.  
  498.                 // Animate the features into their new positions
  499.                 animateFeature($newLeft, direction);
  500.                 animateFeature($newCenter, direction);
  501.                 animateFeature($newRight, direction);
  502.                 // Only want to animate the "hidden" feature if there are more than three
  503.                 if (pluginData.totalFeatureCount > 3) {
  504.                     animateFeature($newHidden, direction);
  505.                 }
  506.             }
  507.  
  508.             // This is used to relegate carousel movement throughout the plugin
  509.             // It will only initiate a move if the carousel isn't currently moving
  510.             // It will set the animation queue to the number of rotations given
  511.             function initiateMove(direction, rotations) {
  512.                 if (pluginData.currentlyMoving == false) {
  513.                     var queue = rotations * pluginData.itemsToAnimate;
  514.                     pluginData.rotationsRemaining = queue;
  515.                     move(direction);
  516.                 }
  517.             }
  518.  
  519.             /**
  520.              * This will find the shortest distance to travel the carousel from
  521.              * one position to another position. It will return the shortest distance
  522.              * in number form, and will be positive to go to the right and negative for left
  523.              */
  524.             function findShortestDistance(from, to) {
  525.                 var goingToLeft = 1, goingToRight = 1, tracker;
  526.                 tracker = from;
  527.                 // see how long it takes to go to the left
  528.                 while ((tracker = getPreviousNum(tracker)) != to) {
  529.                     goingToLeft++;
  530.                 }
  531.  
  532.                 tracker = from;
  533.                 // see how long it takes to to to the right
  534.                 while ((tracker = getNextNum(tracker)) != to) {
  535.                     goingToRight++;
  536.                 }
  537.  
  538.                 // whichever is shorter
  539.                 return (goingToLeft < goingToRight) ? goingToLeft*-1 : goingToRight;
  540.             }
  541.  
  542.             // Move to the left if left button clicked
  543.             $(".leftButton").click(function () {
  544.                 initiateMove(false,1);
  545.             });
  546.  
  547.             // Move to right if right button clicked
  548.             $(".rightButton").click(function () {
  549.                 initiateMove(true,1);
  550.             });
  551.  
  552.             // These are the click and hover events for the features
  553.             pluginData.featuresContainer.children("div")
  554.                 .click(function () {
  555.                     var position = $(this).data('position');
  556.                     if (position == 2) {
  557.                         initiateMove(true,1);
  558.                     } else if (position == pluginData.totalFeatureCount) {
  559.                         initiateMove(false,1);
  560.                     }
  561.                 })
  562.                 .mouseover(function () {
  563.                     if (pluginData.currentlyMoving == false) {
  564.                         var position = $(this).data('position');
  565.                         if (position == 2 || position == pluginData.totalFeatureCount) {
  566.                             $(this).css("opacity",0.8);
  567.                         }
  568.                     }
  569.                 })
  570.                 .mouseout(function () {
  571.                     if (pluginData.currentlyMoving == false) {
  572.                         var position = $(this).data('position');
  573.                         if (position == 2 || position == pluginData.totalFeatureCount) {
  574.                             $(this).css("opacity",0.4);
  575.                         }
  576.                     }
  577.                 });
  578.  
  579.             // Add event listener to all clicks within the features container
  580.             // This is done to disable any links that aren't within the center feature
  581.             $("a", pluginData.containerIDTag).live("click", function (event) {
  582.                 // travel up to the container
  583.                 var $parents = $(this).parentsUntil(pluginData.containerIDTag);
  584.                 // now check each of the feature divs within it
  585.                 $parents.each(function () {
  586.                     var position = $(this).data('position');
  587.                     // if there are more than just feature divs within the container, they will
  588.                     // not have a position and it may come back as undefined. Throw these out
  589.                     if (position != undefined) {
  590.                         // if any of the links on a feature OTHER THAN the center feature were clicked,
  591.                         // initiate a carousel move but then throw the link action away
  592.                         // if the position WAS the center (i.e. 1), then do nothing and let the link pass
  593.                         if (position != 1) {
  594.                             if (position == pluginData.totalFeatureCount) {
  595.                                 initiateMove(false,1);
  596.                             } else if (position == 2) {
  597.                                 initiateMove(true,1);
  598.                             }
  599.                             event.preventDefault();
  600.                             return false;
  601.                         }
  602.                     }
  603.                 });
  604.             });
  605.  
  606.             $(".blip").live("click",function () {
  607.                 // grab the position # that was clicked
  608.                 var goTo = $(this).attr("id").substring(5);
  609.                 // find out where that feature # actually is in the carousel right now
  610.                 var whereIsIt = pluginData.featuresContainer.children("div").eq(goTo-1).data('position');
  611.                 // which feature # is currently in the center
  612.                 var currentlyAt = pluginData.currentCenterNum;
  613.                 // if the blip was clicked for the current center feature, do nothing
  614.                 if (goTo != currentlyAt) {
  615.                     // find the shortest distance to move the carousel
  616.                     var shortest = findShortestDistance(1, whereIsIt);
  617.                     // initiate a move in that direction with given number of rotations
  618.                     if (shortest < 0) {
  619.                         initiateMove(false,(shortest*-1));
  620.                     } else {
  621.                         initiateMove(true,shortest);
  622.                     }
  623.                 }
  624.  
  625.             });
  626.         });
  627.     };
  628.  
  629.     $.fn.featureCarousel.defaults = {
  630.         // If zero, take original width and height of image
  631.         // If between 0 and 1, multiply by original width and height (to get smaller size)
  632.         // If greater than one, use in place of original pixel dimensions
  633.         largeFeatureWidth :     0,
  634.         largeFeatureHeight:             0,
  635.         smallFeatureWidth:      0,
  636.         smallFeatureHeight:             0,
  637.         // how much to pad the top of the carousel
  638.         topPadding:             20,
  639.         // spacing between the sides of the container (pixels)
  640.         sidePadding:            30,
  641.         // the additional offset to pad the side features from the top of the carousel
  642.         smallFeatureOffset:             50,
  643.         // indicates which feature to start the carousel at
  644.         startingFeature:        1,
  645.         // speed in milliseconds it takes to rotate the carousel
  646.         carouselSpeed:          1000,
  647.         // time in milliseconds to set interval to autorotate the carousel
  648.         // set to zero to disable it, negative to go left
  649.         autoPlay:               0,
  650.         // set to true to enable the creation of blips to indicate how many
  651.         // features there are
  652.         counterStyle:           1,
  653.         // true to preload all images in the carousel before displaying anything
  654.         preload:                true,
  655.         // Will only display this many features in the carousel
  656.         // set to zero to disable
  657.         displayCutoff:          0,
  658.         // an easing can be specified for the animation of the carousel
  659.         animationEasing:        'swing'
  660.     };
  661.  
  662. })(jQuery);
  663.  
  664.  
lraido Отправлено: 27 Сентября, 2011 - 09:25:38 • Тема: php как убрать enter у строки • Форум: Вопросы новичков

Ответов: 3
Просмотров: 708
Я сделал данные жеско - строкой.
lraido Отправлено: 18 Сентября, 2011 - 18:03:33 • Тема: php как убрать enter у строки • Форум: Вопросы новичков

Ответов: 3
Просмотров: 708
Доброго времени суток


Вопрос на первый взгляд простой, но для меня превратился в западню.

Дело в том, что обычные переносы строки у меня стрираются.

Этот мейл(который находится в базе данных) никак не хочет автоматически убрать перенос строки, который в него записан.


elviragoldshtein@
yahoo.com



Вручную убрать его невозможно, так как записей в базе данных с такой ошибкой очень много.

Помогите пожалуйста.
lraido Отправлено: 16 Августа, 2011 - 13:51:54 • Тема: Не работает регулярное выражение. • Форум: Вопросы новичков

Ответов: 6
Просмотров: 211
DeepVarvar пишет:
Мелкий пишет:
Ограничивать можно
только потом не забывать экранировать.

lraido хотел бы побеседовать по ICQ, но тебя там просто не бывает.
А предложение в силе. Сегодня после 20:00 по москве выйти в асю сможешь?





В итоге - не получается, а надо!

Решение


PHP:
скопировать код в буфер обмена
  1. |<tr class="oddRowBlack ">(.*?)</tr>|s


То есть:

добавляем s в конец выражения.
lraido Отправлено: 16 Августа, 2011 - 12:46:22 • Тема: Не работает регулярное выражение. • Форум: Вопросы новичков

Ответов: 6
Просмотров: 211
Мелкий пишет:
DeepVarvar пишет:
| - это спецсимвол "или", им нельзя ограничивать паттерн

Можно. Ограничивать можно всем, чем угодно (ну кроме alphanumeric и backslash). Но в регулярке этот символ свою функцию потеряет. Например:


lraido, * по-умолчанию жадная и хватает всё, до чего дотягивается. Про жадность см. тут: http://php.su/lessons/?lesson_17


Значит так?Ему все равно, может неправильная реакция на TR?
PHP:
скопировать код в буфер обмена
  1. |<tr class="oddRowBlack ">(.*)</tr>.*|


Беру примеры отсюда.

http://text[dot]md/primery-reguljarn[dot][dot][dot]razhenij-na-php/

За основу

PHP:
скопировать код в буфер обмена
  1.  
  2.  
  3. if (preg_match('|<title.*?>(.*)</title>|sei', $str, $arr)) $title = $arr[1];
  4.    else $title='';
  5.  


а что такое sei?
lraido Отправлено: 16 Августа, 2011 - 12:39:10 • Тема: Не работает регулярное выражение. • Форум: Вопросы новичков

Ответов: 6
Просмотров: 211
DeepVarvar пишет:
| - это спецсимвол "или", им нельзя ограничивать паттерн


| - да, он ограничивает область.
lraido Отправлено: 16 Августа, 2011 - 12:25:28 • Тема: Не работает регулярное выражение. • Форум: Вопросы новичков

Ответов: 6
Просмотров: 211
Здравствуйте, уважаемые профессиоалы. Улыбка


Из вполне санкцанированного парсера с одного проекта в другой переходят данные. Улыбка


CODE (htmlphp):
скопировать код в буфер обмена
  1.  
  2.  
  3.                 <table width="98%" border = 0  align="center" cellpadding="0" cellspacing="0" bordercolor = >
  4.                   <tr>
  5.                   <td width="87%" align="center"> <div id="outer"><div id="wrapper" style="width:100%;">
  6. <div id="header">
  7. PNR Pax Details</div>
  8. <div id="main" class="dataTable">
  9. <table cellpadding="0" cellspacing="0" border="0" style="width:100%;">
  10. <tr class="evenrow">
  11. <td style="width:10%">Select PAX</td>
  12. <td style="width:20%">Name</td>
  13. <td style="width:20%">Surname</td>
  14. <td style="width:20%">Gender</td>
  15. <td style="width:15%">Date of birth</td>
  16. <td style="width:3%">FF</td>
  17. <td style="width:7%"></td>
  18. </tr>
  19. <tr>
  20. <td style="height:2px;" colspan="7"></td></tr>
  21. <tr class="oddRowBlack ">
  22. <td valign="top"  style=""><input type="radio" name="PAXISN" value="66090070" checked>
  23. </td>
  24. <td valign="top"  style="">DAVIT</td>
  25. <td valign="top"  style="">TCHUMBURIDZE</td>
  26. <td valign="top"  style="">Mr.</td>
  27. <td valign="top"  style=""></td>
  28. <td valign="top"  style=""></td>
  29. <td valign="top"  style=""><input type="checkbox" id="PAX66090070" name="PAX66090070"  value="T" ></td>
  30. </tr>
  31. </table>
  32. </div>
  33. <div id="footer"> </div>
  34. </div>
  35. </div>
  36. </td>
  37.                   </tr>
  38.             </table><p>
  39.  
  40.  


Чтобы взять содержимое из


CODE (htmlphp):
скопировать код в буфер обмена
  1.  
  2.  
  3. <tr class="oddRowBlack ">
  4. <td valign="top"  style=""><input type="radio" name="PAXISN" value="66090070" checked>
  5. </td>
  6. <td valign="top"  style="">DAVIT</td>
  7. <td valign="top"  style="">TCHUMBURIDZE</td>
  8. <td valign="top"  style="">Mr.</td>
  9. <td valign="top"  style=""></td>
  10. <td valign="top"  style=""></td>
  11. <td valign="top"  style=""><input type="checkbox" id="PAX66090070" name="PAX66090070"  value="T" ></td>
  12. </tr>
  13.  
  14.  



Пишу следующее регулярное выражение.

$data1 - пришедший код


CODE (htmlphp):
скопировать код в буфер обмена
  1.  
  2.  
  3. preg_match_all('|<tr class="oddRowBlack ">(.*)</tr>|',$data1,$tourist_rows,0);
  4.  
  5.  


И ничего не выводит. Огорчение

Стоит записать

preg_match_all('|<td valign="top" style="">(.*)</td>|',$data1,$tourist_rows,0);

Начинает выводить, но ещё прихватывает кучу всего, что недолжно. Однако


Как взять содержимое этого тэга? А ещё лучше содержимое td в этом tr.

Помогите пожалуйста. Улыбка
lraido Отправлено: 27 Июля, 2011 - 17:51:57 • Тема: Передать id таблицы • Форум: Вопросы новичков

Ответов: 2
Просмотров: 166
CODE (htmlphp):
скопировать код в буфер обмена
  1.  
  2.  
  3. <?
  4.  
  5.  
  6. $sql = "select * from `имя_таблицы`":
  7.  
  8. $query = mysql_query($sql);
  9.  
  10. While($row=mysql_fetch_array($query))
  11. {
  12.  
  13. echo "<a href='путь к файлу стрипта?id=".$row['id']."'></a>";
  14.  
  15. }
  16.  
  17.  
  18. ?>
  19.  
  20.  
  21.  
  22.  



Так мы выводим данные для таблицы

А на файле - где сидит обработчик используй переменную $_GET['id']

вставляй эту переменную куду хочешь. Улыбка
lraido Отправлено: 11 Июля, 2011 - 08:58:57 • Тема: Уважаемые професионалы, помогите. • Форум: Вопросы новичков

Ответов: 3
Просмотров: 216
Дело в том, что мы отсюда не можем узнать не мейл покупателя, не его имя. Оно должно устанавливаться во время платежа вна пейпале. В инвойсе оно вставляется, значит и на сайт прислаться может. Вопрос - как?
lraido Отправлено: 10 Июля, 2011 - 18:40:54 • Тема: Уважаемые професионалы, помогите. • Форум: Вопросы новичков

Ответов: 3
Просмотров: 216
Доброго времени суток.

Имеется форма

CODE (html):
скопировать код в буфер обмена
  1.  
  2.  
  3. <form action="https://www.paypal.com/cgi-bin/webscr" method="post">
  4. <input type="hidden" name="cmd" value="_s-xclick">
  5. <input type="hidden" name="hosted_button_id" value="xxxxxxx">
  6.  
  7. <input type="hidden" name="return" value="xxxxxxx">
  8. <input type="hidden" name="cancel_return" value="xxxxxxx">
  9.  
  10. <input type="image" src="https://www.paypalobjects.com/en_US/IL/i/btn/btn_paynowCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
  11. <img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1">
  12. </form>
  13.  
  14.  
  15.  


Есть острая необходимость, данные платежа(такие как имя покупателя и его мейл) отправлять обратно на сайт и там обрабатывать.


PHP:
скопировать код в буфер обмена
  1.  
  2.   $postdata="";
  3.   foreach ($_POST as $key=>$value) $postdata.=$key."=".urlencode($value)."&";
  4.   $postdata .= "cmd=_notify-validate";
  5.   echo $postdata.'<br>';
  6.  
  7.  
  8.   $curl = curl_init("https://www.paypal.com/cgi-bin/webscr");
  9.   curl_setopt ($curl, CURLOPT_HEADER, 0);
  10.  
  11.   curl_setopt ($curl, CURLOPT_POST, 1);
  12.   curl_setopt ($curl, CURLOPT_POSTFIELDS, $postdata."&");
  13.  
  14.  
  15.  
  16.   curl_setopt ($curl, CURLOPT_SSL_VERIFYPEER, 0);
  17.  
  18.   curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
  19.   curl_setopt ($curl, CURLOPT_SSL_VERIFYHOST, 1);
  20.  
  21.  
  22.  
  23.   $response = curl_exec ($curl);
  24.  


пишу такой скрипт, но на страницу, куда должен возвращаться, он не пересылает данные. Совсем никакие.

Что делать? Уже который день мучаюсь!
lraido Отправлено: 03 Июня, 2011 - 16:48:53 • Тема: Уважаемые професионалы • Форум: Регулярные выражения

Ответов: 1
Просмотров: 116
Добрый день, делаю перевод на сайте.

Есть простая и эффективная функиця, которая переводит слова. Улыбка

PHP:
скопировать код в буфер обмена
  1.  
  2.         $sql = "select * from LangSettings where lang_id='".$l_id."'";
  3.  
  4.         $query = mysql_query($sql);
  5.  
  6.         while($row = mysql_fetch_array($query))
  7.         {
  8.                 $txt = str_replace($row['alias'],$row['value'],$txt);
  9.         }
  10.  


К сожалению когда перевожу на английский язык то прихватываются ещё и тэги. Огорчение

Как написать функцию preg_replace, чтобы она не меняла то, что в тэгах.
Подмигивание
Помогите пожалуйста.
lraido Отправлено: 10 Марта, 2011 - 15:52:16 • Тема: Доступ к apache из интернета • Форум: Apache и другие веб-серверы

Ответов: 14
Просмотров: 6418
Про 1443 порт.

Признаки вот такие. Есть компьютер(принадлежащий шефу и находится не в нашей сети) который испльзуя такой линк ip:1443/директория с сайтом/ входит на этот сайт.

Остальные же компьютеры в сети просто используют его локальный адрес(сайт нужен был строго для внутренних нужд).

Все было хорошо,пока в сети не появился мой компьютер, со своим сервером для тестирования того, что я программирую (как вы уже догадались - РНР-скрипты), и шефу хочется смотреть что творится на моих тестовых сайтах.

А с помощью каких средств Windows-а(программных) или железных можно реализовать вышеописаные перенаправления(как вы наверное уже догадались, в сервернх технологиях мне удалось общаться только с апачом+РНР+базой данных)?


P.S. Спасибо, что уделяете мне свое время! Улыбка
lraido Отправлено: 10 Марта, 2011 - 14:36:21 • Тема: Доступ к apache из интернета • Форум: Apache и другие веб-серверы

Ответов: 14
Просмотров: 6418
EuGen пишет:
Вот этот его "сосед", судя по всему и есть Ваш интернет-шлюз, про который я Вам написал. Сделать конечно можно
Здесь вариантов несколько. На Вашем компьютере изменить порт веб-сервера, например,
Listen 8080
А на шлюзе перенаправлять все запросы для этого порта на нужный компьютер в локальной сети. Тогда по запросу http://IP[dot]вашего[dot]интернет[dot]шлюза:8080 вы попадете на этот самый локальный компьютер. Минус данного подхода более чем очевиден - невозможность развертывания таким образом нескольких веб-сайтов (так как виртуальные хосты использовать не получится)
Второй вариант - более правильный - выделить внешний адрес для нужного компьютера и настроить маршрутизацию внутри сети, к которой подключен интернет шлюз. Иными словами, маршрут для этого адреса должен проходить через этот самый шлюз, который уже и будет маршрутизировать его на нужную машину локальной сети.
И третий вариант - выделить внешний адрес и подключить локальный компьютер напрямую к сети провайдера (таким образом он будет иметь туда прямой доступ как и интернет-шлюз).
На мой взгляд, лучше всего подходит второй вариант, так как вы достигаете цели и одновременно исключаете прямой доступ к локальной сети, минуя интернет-шлюз.




Да! Второй вариант мне тоже больше всего нравится.

Что нужно для этого сделать?

Как я понял надо - позвонить провайдеру, сказать ему - выдели мне новый внешний Ip-адрес.
Настраивать маршрутизацию внутри сети я не умею к сожалению(могу научиться).
Что такое шлюз - я тоже не знаю.


Что мне сказать своему шефу? Который вряд ли поймет всей премудрости этой задумки(если и я во всем не разобрался).


Еще одна премудрость заключается в том, что доступ к сайту на соседнем компьютере осуществляется только через 1433 порт, а другие подключения как вы уже догадались ведут к вот такому сообщению.

A username and password are being requested by http://тот[dot]самый[dot]ip[dot]адрес . The site says: "DSL Router"

с формами ввода логина+пароля


(кстати шеф сказал, что лучше как-то использовать уже имеющийся выделенный ip который не помешает работе соседнего компьютера) - значит вроде подходит первый вариант?
lraido Отправлено: 10 Марта, 2011 - 13:59:18 • Тема: Доступ к apache из интернета • Форум: Apache и другие веб-серверы

Ответов: 14
Просмотров: 6418
EuGen пишет:
Думаю, Ваша проблема пока что в непонимании разницы между локальными адресами и адресами в WAN.
В настройках Apache оставьте вот это:
Listen 80
Внешний IP-адрес нужен, чтобы в глобальной сети любой компьютер мог понять, куда именно отсылать запрос. Локальные адреса действуют только в пределах "Вашей сети". Обычно это адреса в диапазоне
192.168.0.0/16
10.0.0.0/8
(например, 192.168.2.5 - пример такого адреса)
Существует или нет внешний адрес у Вашей машины - вопрос к провайдеру. По указанному в сообщении выше адресу 2ip.ru Вы увидите внешний адрес своего интернет-шлюза (то есть того компьютера, через который Ваша сеть подключена к интернету - обычно это подконтролный провайдеру узел). И адрес этот вовсе не обязан быть Вашим внешним адресом, так как чаще всего целые локальные сети находятся за одним шлюзом (это технология NAT). Надеюсь, понятно описал.

Так что в любом случае Вам нужно связаться с провайдером и попросить его о выделении внешнего IP-адреса (если такогого еще не имеется)






В сети уже есть компьютер, который имеет внешний ip и к которому обращаюется, и который имеет серверные функции.

В этой же сети находится мой компьютер, с локальным адресом.


http://2ip[dot]ru как раз воспользовался.

dyndns - а что это такое?

Может есть возможность сделать компьютер в моей сети таким же глобальным, как его сосед?

Страниц (5): « 1 2 [3] 4 5 »
Powered by PHP  Powered By MySQL  Powered by Nginx  Valid CSS  RSS

 
Powered by ExBB FM 1.0 RC1. InvisionExBB