【问题标题】:automated scrolling text in div'sdiv中的自动滚动文本
【发布时间】:2012-11-24 19:44:35
【问题描述】:

我看到已经发布了一个堆栈问题:

[问题]:Text in div - automated scrolling with jQuery - jsFiddle inside>

我的问题是,是否可以在每个段落中的文本或分隔的 div 处于主视图中时突出显示它们(粗体、背景颜色等),而 p 或 div 离开/进入滑块盒子褪色了?

就像引用的 jsfiddle 一样,您有一个 div 容器,其中包含 4、5、6、... div 或 p,其中一个 div 或 p 可见,而其上方和下方的 div 或 p 只有一半将是可见的(褪色),而剩余的溢出是隐藏的。

谢谢。

【问题讨论】:

  • 假设出于本练习的目的,每个 div 或段落的高度和宽度相同。所以容器是 110px 高,60px 宽,而里面的段落或 div 是 50px x 50px。

标签: javascript jquery css scroll jsfiddle


【解决方案1】:

如果我理解正确,您正在寻找这样的效果:

http://jsfiddle.net/2RRWS/

我的代码采用 html 结构,如:

<div id="scrollContainer">
   <p>Some text</p>
   <p>More text</p>
   ...
</div>

还有一些 CSS 来适当地设置包含 div 的宽度/高度。它还为“暗淡”和“突出显示”的段落假设了一些类。

可能有一种更清洁的方法可以做到这一点,但这只是我拼凑起来的,它似乎有效,所以......

var $container = $("#scrollContainer"),
    $ps = $container.find("p"),
    containerHeight = $container.height(),
    contentHeight = 0,
    scrollTop = 0;

// figure out the height of the content
$ps.each(function() {
    contentHeight += $(this).outerHeight();
});

// add some blank space at the beginning and end of the content so that it can
// scroll in from the bottom
$("<div></div>").css("height", 400).appendTo($container).clone().prependTo($container);

setInterval(function() {
    if (paused)
        return;
    // if we've gone off the end start again
    if (scrollTop > contentHeight + containerHeight)
        scrollTop = 0;
    // scroll up slightly
    $container.scrollTop(scrollTop++);

    $ps.removeClass("highlighted")   // for each paragraph...
       .addClass("dimmed")           // dim it
       .each(function() {            // unless it is in view
           var $this = $(this),
               top = $this.position().top,
               height = $this.height();
           if (top > 0 && top + height < containerHeight)
                    $(this).addClass("highlighted").removeClass("dimmed");
    });
}, 20);

$container.hover(function() {
    paused = true;
}, function() {
    paused = false;
});

编辑:更新以根据评论实现“暂停”功能。 http://jsfiddle.net/2RRWS/8/

【讨论】:

  • 太棒了,正是我试图创造的。我只是缩短了容器高度,因此在任何给定时间都只突出显示了一个段落。我唯一的另一个问题是是否可以使用光标添加暂停/继续切换功能?
  • 好的,我已经更新了问题中显示的代码,并提供了第二个演示小提琴的链接。每当您通过setInterval() 进行连续处理时,您都可以通过让函数根据上面的if (paused) return; 语句检查标志来轻松暂停它。然后根据需要设置标志。 (setInterval() 在暂停时继续调用您的函数,但该函数不执行任何操作。我发现这比调用 clearInterval() 并不得不再次调用 setInterval() 重新启动要少。)
  • 感谢您的帮助。解释得也很好。
猜你喜欢
  • 2010-12-06
  • 1970-01-01
  • 2012-11-29
  • 1970-01-01
  • 1970-01-01
  • 2016-10-25
  • 2015-08-20
  • 2022-01-12
  • 2013-05-18
相关资源
最近更新 更多