我正在尝试获取div.newsticker
的宽度
并试图在动画和附加中使用它作为变量。
然而,这似乎不起作用。我该如何解决?
这是我的代码。
jQuery(document).ready(function () {
var width = jQuery("div.newsticker").width()+"px";
});
// To get resize notification
jQuery(window).on("resize", function() {
var width = jQuery(".newticker").width()+"px";
});
function showComments(time){
var comments = findComments(time);
if(comments[0]){
$('.newsticker p').animate({"marginLeft":width,"opacity":".0"}, 600).fadeOut(100);
$('.newsticker').append("<p style='margin-left:"+width+";opacity:0'>"+comments[0].message+"</p>");
$('.newsticker p').animate({"marginLeft":"0px","opacity":"1"}, 600);
}
}
原始代码
function showComments(time){
var comments = findComments(time);
if(comments[0]){
$('.newsticker p').animate({"marginLeft":"400px","opacity":".0"}, 600).fadeOut(100);
$('.newsticker').append("<p style='margin-left:400px;opacity:0'>"+comments[0].message+"</p>");
$('.newsticker p').animate({"marginLeft":"0px","opacity":"1"}, 600);
}
}
答案 0 :(得分:1)
您需要使用正确的范围声明变量。
var width = '';
jQuery(document).ready(function () {
width = jQuery("div.newsticker").width()+"px";
});
// To get resize notification
jQuery(window).on("resize", function() {
width = jQuery(".newsticker").width()+"px";
});
function showComments(time){
var comments = findComments(time);
if(comments[0]){
$('.newsticker p').animate({"marginLeft":width,"opacity":".0"}, 600).fadeOut(100);
$('.newsticker').append("<p style='margin-left:"+width+";opacity:0'>"+comments[0].message+"</p>");
$('.newsticker p').animate({"marginLeft":"0px","opacity":"1"}, 600);
}
}