2016-07-22 108 views
0

我想在我的应用程序上进行水平滚动。有很多例子,但我找到了一个符合我需要的例子。但是,当我尝试它时,它只是不工作,因为它应该。请看看,并告诉我是什么问题:javascript水平滚动文本

<!DOCTYPE html> 
<html> 
<head> 
<style> 
div.marquee { 
    white-space:no-wrap; 
    overflow:hidden; 
} 
div.marquee > div.marquee-text { 
    white-space:nowrap; 
    display:inline; 
    width:auto; 
} 
</style> 
<script> 
var marquee = $('div.marquee'); 
console.log(marquee); 
marquee.each(function() { 
    var mar = $(this),indent = mar.width(); 
    mar.marquee = function() { 
     indent--; 
     mar.css('text-indent',indent); 
     if (indent < -1 * mar.children('div.marquee-text').width()) { 
      indent = mar.width(); 
     } 
    }; 
    mar.data('interval',setInterval(mar.marquee,1000/60)); 
}); 
</script> 
</head> 
<body> 
<div class='marquee'> 
    <div class='marquee-text'> 
     Testing this marquee function 
    </div> 
</div> 

</body> 
</html> 

更新 有一个在控制台没有错误: enter image description here

+0

那么....你可以使用旧的''标签。 –

+4

@GavinThomas它不是1998;)是[废弃](http://caniuse.com/#search=marquee),不要使用它 –

+0

1)除了与旧的兼容性,不要使用'setInterval'动画浏览器,'requestAnimationFrame'和CSS动画更可靠。 2)每帧查找和设置属性如“text-indent”和“width”对性能不利,变换效果更好。 3)你真的需要一个大帐篷吗? ;) – gcampbell

回答

4

你忘了,包括jQuery的在您的网站。否则,它按预期工作(至少我是这么认为的)。

$(document).ready(function() { 
 
    var marquee = $('div.marquee'); 
 
    console.log(marquee); 
 
    marquee.each(function() { 
 
     var mar = $(this),indent = mar.width(); 
 
     mar.marquee = function() { 
 
      indent--; 
 
      mar.css('text-indent',indent); 
 
      if (indent < -1 * mar.children('div.marquee-text').width()) { 
 
       indent = mar.width(); 
 
      } 
 
     }; 
 
     mar.data('interval',setInterval(mar.marquee,1000/60)); 
 
    }); 
 
});
div.marquee { 
 
    white-space:no-wrap; 
 
    overflow:hidden; 
 
} 
 
div.marquee > div.marquee-text { 
 
    white-space:nowrap; 
 
    display:inline; 
 
    width:auto; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class='marquee'> 
 
    <div class='marquee-text'> 
 
     Testing this marquee function 
 
    </div> 
 
</div>

编辑:加入$(document).ready(),以确保元件将被加载。

1

在执行脚本之前等待页面加载。

<script> 
$(document).ready(function(){ 
var marquee = $('div.marquee'); 
console.log(marquee); 
marquee.each(function() { 
    var mar = $(this),indent = mar.width(); 
    mar.marquee = function() { 
     indent--; 
     mar.css('text-indent',indent); 
     if (indent < -1 * mar.children('div.marquee-text').width()) { 
      indent = mar.width(); 
     } 
    }; 
    mar.data('interval',setInterval(mar.marquee,1000/60)); 
}); 
}); 
</script> 

故见this问题,不要忘记在头 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>