jQuery News Ticker:.remove() dom 效果 [英] jQuery News Ticker: .remove() dom effect

查看:20
本文介绍了jQuery News Ticker:.remove() dom 效果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作新闻自动收报机(没有任何插件).我使用 jQuery UI 的 animate 方法让新闻从右向左移动.

I'm trying to make a news ticker (without any plug-in). I use jQuery UI's animate method to make the news move from right to left.

我正在删除第一个新闻 (li) 并将其附加到列表的末尾 (ul) 并重新调整 margin-left.这不是为了每次循环后都得到一个很长的空白.

I'm removing the first news (li) and attaching it to the end of the list (ul) and readjusting the margin-left. This is not to get a long white space every after cycle.

问题是...当我 .remove() 第一个消息时,它会导致不受欢迎的 UI 故障(至少对我而言).这部分:

Problem is... when I .remove() the first news, it's causing an undesirable UI glitch (at least for me). This part:

leftMargin = leftMargin + $('.news-ticker-display li:first').width() - 2;
$('.news-ticker-display li:first').remove();

这是我的 jsFiddle 链接:

任何帮助/建议/评论/替代方案将不胜感激.抱歉,我想不出有建设性的标题.哈哈

Any help/suggestion/comment/alternative will be greatly appreciated. Sorry I can't think a constructive title for this. lol

推荐答案

您的代码正在等待下一个动画循环来更新左边距,这会在几帧之后发生.您需要立即设置它(与 remove() 在同一帧上)以避免视觉故障.

Your code is waiting fo the next animate cycle to update the left margin, which happens a few frames later. You need to set it immediately (on the same frame as the remove()) to avoid visual glitches.

var leftMargin, scrollSpeed;
var playScroll = true;

scrollSpeed = 5;
leftMargin = 0;

function autoPlay() {
    if (playScroll) {
        $('.news-ticker-display').animate({ marginLeft: --leftMargin }, scrollSpeed, "linear", function () {
            var $first = $('.news-ticker-display li:first');
            var width = $first.outerWidth();
            if (leftMargin < -width) {
                $first.clone().appendTo('.news-ticker-display ul');
                leftMargin = leftMargin + width;
                $first.remove();
                $(this).css({marginLeft: --leftMargin});
            }
            autoPlay();
        });
    }
}

autoPlay();

JSFiddle: https://jsfiddle.net/TrueBlueAussie/8djw6qen/8/

  • 您会看到我使用临时变量简化了代码.最好不要重复 jQuery 选择器.
  • 您还需要使用outerWidth(),而不是尝试补偿边框.
  • 我加快了测试的动画速度(否则需要很长时间才能看到故障):) 只需将其设置回您自己的值即可.
  • 您可以使用上下文减少第一个选择器.例如var $first = $('li:first', this);
  • .first() 传统上比在选择器中使用 :first 更快,但这在这里真的无关紧要:)
  • You will see I have simplified the code using temp vars. It is good practice to not repeat jQuery selectors.
  • You also need to use outerWidth(), rather than try to compensate for the border.
  • I sped up the animation for the testing (taking too long to see the glitches otherwise) :) Just set it back to your own value.
  • You can reduce the first selector using a context. e.g. var $first = $('li:first', this);
  • .first() is traditionally faster than using :first in a selector, but that really does not matter here :)

这篇关于jQuery News Ticker:.remove() dom 效果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆