php - 使用一个 javascript 自定义滚动三个列表

标签 php javascript html css scroll

我刚刚有点失控,我有一个用 PHP 填充的列表,以及一个在列表上创建滚动效果的 javascript 文件,这样我就可以上下滚动。

但我需要在同一页上放置三个这样的列表框,当我将另外两个列表框放入其中时,它们不会生成,只有第一个是。我需要能够在页面上显示所有三个。任何对此的帮助都会很棒!

亲切的问候, 阿利斯泰尔

<div id="mContainer"> 
<div id="upArrow"></div> 
<div id="nContainer"> 
<ul id="listContainer"> 
<?php
connect();
$sql="SELECT drivers_id, firstname,image FROM drivers"; 
$result=mysql_query($sql); 
while ($row=mysql_fetch_array($result)){
echo "<li><a id='".$row['drivers_id']."' onclick='return showPic(this)' onfocus='this.hideFocus=true;' href='".$row['image']."'>".$row['firstname']."</a></li>";
}
?>
</ul> 
</div> 
<div id="downArrow"> 
</div> 
</div> 

**JAVASRIPT FILE BELOW**

window.onload=init;

var d=document;
var lContainer;             // object reference for the UL

var currentTop=0;           // the current Y position of the UL
var zInterval = null;       // animation thread interval
var direction;              // direction we're scrolling the UL. 0==up, 1==down
var startTop=0;             // the starting top of the UL
var scrollRate=8;           // initial rate of scrolling
var scrollTick=0;           // keeps track of long we've scrolled so we can    slow it down accordingly
var listHeight=60;          // the current height of the UL
var MAX_SCROLL_TICK=4;      // the maximum value of scrollTick before it's   reset
var MIN_LIST_HEIGHT=145;    // contracted height of the list
var REBOUND = 0;            // the value of scrollRate when we stop scrolling

function init() {
if(!d.getElementById)return; // bail out if this is an older browser

up=d.getElementById("upArrow");
down=d.getElementById("downArrow");

// apply onclick behaviors to the up arrow, down arrow and expansion control     elements
down.onmousedown=function(){
scrollObjects(0);
}
up.onmousedown=function(){
scrollObjects(1);
}

lContainer = d.getElementById("listContainer");

d.getElementById("nContainer").style.height=MIN_LIST_HEIGHT+"px";
}

function scrollObjects(dir) {
if(zInterval)return; // already scrolling.
if((!dir && currentTop<=-300) || (dir && currentTop==0))
return; // dont scroll up if we're at the top or down if at the bottom of the list

direction=dir;
zInterval=setInterval("animate()",20);
}

function animate() {
// increment or decrement currentTop based on direction
if(!direction) {
currentTop-=scrollRate;
} else {
currentTop+=scrollRate;
}
scrollTick++;   
if(scrollTick>=MAX_SCROLL_TICK) {
scrollRate--; // slow the scroll rate down for a little style
scrollTick=0;
}

lContainer.style.top=currentTop+"px";
if(scrollRate<=REBOUND) {
// scroll is finished. clear the interval and reset vars for the next    scroll
clearInterval(zInterval);
zInterval=null;
startTop=currentTop;
scrollTick=0;
scrollRate=8;
}
}

最佳答案

首先,升级到 jQuery .您最终会为自己的所作所为感到非常高兴。

接下来,不要使用内联 JavaScript!高兴的部分也是如此。

这是 jQuery 中的现有功能。多列表版本在首屏下方。

添加:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>

(或加载一个版本的 jQuery 文件到您自己的网站。)

PHP:

<div id="mContainer">
  <div id="upArrow"></div>
  <div id="nContainer">
    <ul id="listContainer">
      <?php
        connect();
        $sql    = "SELECT drivers_id, firstname, image FROM drivers";
        $result = mysql_query($sql);
        while ($row=mysql_fetch_array($result) ) {
          echo "<li><a id='".$row['drivers_id']."' href='".$row['image']."'>".$row['firstname']."</a></li>";
        }
      ?>
    </ul>
  </div>
  <div id="downArrow"></div>
</div>

额外的 CSS:

ul#listContainer li > a:focus {
    outline: none;
}

JavaScript:

$(document).ready (init);

//--- Global variables!
var lContainer;                 // object reference for the UL
var currentTop      = 0;        // the current Y position of the UL
var zInterval       = null;     // animation thread interval
var direction;                  // direction we're scrolling the UL. 0==up, 1==down
var startTop        = 0;        // the starting top of the UL
var scrollRate      = 8;        // initial rate of scrolling
var scrollTick      = 0;        // keeps track of long we've scrolled so we can    slow it down accordingly
var listHeight      = 60;       // the current height of the UL
var MAX_SCROLL_TICK = 4;        // the maximum value of scrollTick before it's   reset
var MIN_LIST_HEIGHT = 145;      // contracted height of the list
var REBOUND         = 0;        // the value of scrollRate when we stop scrolling

function init() {

    //-- Activate click and focus handlers on the li elements.
    $("ul#listContainer li > a").click ( function () { showPic (this); } )
                                // This next is IE only!  use CSS.
                                .focus ( function () { this.hideFocus=true; } );

    //-- Apply onclick behaviors to the up/down arrow and expansion control elements.
    $("#downArrow").mousedown ( function () { scrollObjects (0); } );
    $("#upArrow")  .mousedown ( function () { scrollObjects (1); } );

    lContainer = $("#listContainer");

    $("#nContainer").css ('height', MIN_LIST_HEIGHT + "px");
}

function scrollObjects(dir) {
    if (zInterval) return; // already scrolling.

    // dont scroll up if we're at the top or down if at the bottom of the list
    if ((!dir && currentTop <= -300) || (dir && currentTop == 0)) return;

    direction = dir;
    zInterval = setInterval (animate, 20);
}

function animate() {
    // increment or decrement currentTop based on direction
    if (!direction) {
        currentTop -= scrollRate;
    } else {
        currentTop += scrollRate;
    }
    scrollTick++;
    if (scrollTick >= MAX_SCROLL_TICK) {
        scrollRate--; // slow the scroll rate down for a little style
        scrollTick = 0;
    }

    lContainer.css ('top', currentTop + "px");
    if (scrollRate <= REBOUND) {
        // scroll is finished. clear the interval and reset vars for the next scroll
        clearInterval(zInterval);
        zInterval = null;
        startTop = currentTop;
        scrollTick = 0;
        scrollRate = 8;
    }
}


See this in action at jsFiddle.




多列表版本:

现在,借助 jQuery 的强大威力,我们将:

  1. 启用多列表操作。
  2. 减少对“魔数(Magic Number)”维度的依赖。
  3. 修复明显的过度滚动问题。
  4. 让点击并按住按用户期望的方式工作。

首先,将所有容器和箭头 id 更改为类,如下所示:

<div class="mContainer">
    <div class="upArrow"></div>
    <div class="nContainer">
        <ul class="listContainer">
            ... ...
        </ul>
    </div>
    <div class="downArrow"></div>
</div>

一定要更改 CSS 以匹配,并且不要使用内联 JS,这将在下面处理。

然后 JavaScript 变成:

$(document).ready (init);

function init() {

    //-- Activate click and focus handlers on the li elements.
    $("ul.listContainer li > a").click ( function () { showPic (this); } )
                                // This next is IE only!  use CSS.
                                .focus ( function () { this.hideFocus=true; } );

    //-- Initialize the scroll controls for every list in an mContainer.
    $("div.mContainer").each ( function (J) {
        var jNode   = $(this);
        jNode.data ('OurScrollObject', new ListScroll (jNode) );
    } );
}


/*--- ListScroll object.  This lets us (1) avoid global variables, and (2) keep each
    each list's data separate.
*/
function ListScroll (   contNode,           //--Required: jQuery wrapper of the container node.
                        INIT_SCROLL_RATE,   //--Optional: Initial rate of scrolling.
                        MAX_SCROLL_TICK,    //--Optional: The maximum value of scrollTick before it's reset.
                        MIN_LIST_HEIGHT,    //--Optional: Contracted height of the list.
                        REBOUND             //--Optional: The value of scrollRate when we stop scrolling.
                    )
{
    //--- Set constants to default values as needed.
    var INIT_SCROLL_RATE    = INIT_SCROLL_RATE  ||    8;
    var MAX_SCROLL_TICK     = MAX_SCROLL_TICK   ||    4;
    var MIN_LIST_HEIGHT     = MIN_LIST_HEIGHT   ||  145;
    var REBOUND             = REBOUND           ||    0;

    var listHeight          = contNode.find ("ul.listContainer").outerHeight (true);
    var scrollUpLimit       = MIN_LIST_HEIGHT - listHeight;

    //--- Init state variables.
    var currentTop          = 0;    // The current Y position of the UL.
    var startTop            = 0;    // The starting top of the UL.
    var scrollTick          = 0;    // Keeps track of how long we've scrolled so we can slow down accordingly.
    var scrollRate          = INIT_SCROLL_RATE;
    var bGoDown             = true; // Are we scrolling down?
    var zInterval           = null; // Tracks the animation, interval timer.
    var bStopRequested      = false;

    //--- Apply onclick behaviors to the up/down arrow elements.
    contNode.find (".upArrow, .downArrow").bind ("mousedown mouseup", scrollObjects);

    //--- Set the list's visible height.
    contNode.find (".nContainer").height (MIN_LIST_HEIGHT);


    function scrollObjects (zEvent) //-- zEvent is sent to event listeners automatically.
    {
        var bClickUpBtn = $(this).hasClass ('upArrow');
        var bMouseUp    = (zEvent.type == 'mouseup');

        /*--- Here are the states we want to act on:
            1) Were we already scrolling this list?
            2) Has the user signaled a desire to scroll (mousedown)?
            3) Has the user signaled to scroll scrolling (mouseup)?
            4) Has the user signaled to STOP RIGHT NOW, by clicking the opposite direction
               from the scroll direction?
        */
        if (bMouseUp  &&  ! zInterval) {
            //--- Already stopped before user released the mouse.
            return;
        }
        if (! bMouseUp  &&  zInterval  &&  bGoDown != bClickUpBtn) {
            //--- Already scrolling in the currently-commanded direction.
            return;
        }

        if (zInterval) {
            //--- Already scrolling
            if (bMouseUp) {
                //--- Soft stop commanded (can coast down).
                bStopRequested = true;
            }
            else {
                //--- User must clicked in the opposite direction of the current scroll.
                stopScroll ();
                return;
            }
        }
        else {
            //--- Not scrolling yet

            if (bBoundsCheck (bClickUpBtn) ) {
                //--- Don't scroll beyond the top or bottom of the list.
                return;
            }
            bGoDown     = ! bClickUpBtn;
            zInterval   = setInterval (scrollList, 20);
        }
    }


    function bBoundsCheck (bGoingUp) {
        /*--- Keeps the list from scrolling out of bounds.
            returns true if clipping (would have) occured.
        */
        if (bGoingUp    &&  currentTop <= scrollUpLimit) {
            currentTop  = scrollUpLimit;
            return true;
        }
        if ( ! bGoingUp &&  currentTop >= 0) {
            currentTop  = 0;
            return true;
        }
        return false;
    }


    function stopScroll () {
        //--- Resets the state variables and clears the animation timer.
        clearInterval (zInterval);
        zInterval       = null;
        startTop        = currentTop;
        scrollTick      = 0;
        scrollRate      = INIT_SCROLL_RATE;
        bStopRequested  = false;
    }


    function scrollList () {
        //--- Increment or decrement currentTop based on direction.
        if (bGoDown)    currentTop += scrollRate;
        else            currentTop -= scrollRate;

        if (bBoundsCheck ( ! bGoDown) ) {
            stopScroll ();
            contNode.find (".listContainer").css ('top', currentTop + "px");
            return;
        }
        contNode.find (".listContainer").css ('top', currentTop + "px");

        scrollTick++;
        //if (scrollTick >= MAX_SCROLL_TICK  ||  bStopRequested) { NO! Not ergo.
        if (bStopRequested) {
            scrollRate--; // slow the scroll rate down for a little style
            scrollTick = 0;
        }

        if (scrollRate <= REBOUND) {
            // Scroll is finished. clear the interval and reset vars for the next scroll.
            stopScroll ();
        }
    }
}


See it in action at jsFiddle.

这是 a handy jQuery Reference .


更新:
要更改哪个箭头指向哪个方向,请更改此行:

var bClickUpBtn = $(this).hasClass ('upArrow');

收件人:

var bClickUpBtn = $(this).hasClass ('downArrow');  

See the Fiddle.

关于php - 使用一个 javascript 自定义滚动三个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7045147/

相关文章:

javascript - 如何在javascript中找出char的keycode值

html - 内部元素的垂直对齐

javascript - 如何将值(value)从引导模态 child 传递给 parent ?

php - 使用 yml 配置向现有供应商包实体添加新字段

javascript - 如何创建可扩展的 Angular 应用程序结构?

javascript - 使用 VueJs 相似的对象是不同的

html 行高与小写重叠

php - 如何在wordpress中插入自定义图像和html

php - 无法在 Phonegap android 中使用 AJAX、jQuery 和 php 将数据存储在 mysql 中

php - MySQL:使用单个输入搜索多列(GoogleMaps 样式)