如何在javascript中重新计算变量

how to re-calculate variables in javascript

本文关键字:计算 变量 新计算 javascript      更新时间:2023-09-26
function scrollContent(){
    var div = $('#scrolling-content'),
                 ul = $('ul.image'),
                 // unordered list's left margin
                 ulPadding = 0;
    //Get menu width
    var divWidth = div.width();
    //Remove scrollbars
    div.css({overflow: 'hidden'});
    //Find last image container
    var lastLi = ul.find('li:last-child');
    //When user move mouse over menu
    div.mousemove(function(e){
    //As images are loaded ul width increases,
    //so we recalculate it each time
    var ulWidth = lastLi[0].offsetLeft + lastLi.outerWidth() + ulPadding;   
    var left = (e.pageX - div.offset().left) * (ulWidth-divWidth) / divWidth;
      div.scrollLeft(left);
    });     
}

这是我如何滚动我的图像列表。问题是#scrolling-content元素的大小是动态的。它改变窗口大小。,

$(window).resize(function() {
        $("#scrolling-content").css("width",$(window).width() + "px");
        $("#scrolling-content").css("height",($(window).height()-400) + "px");
});

所以当用户改变窗口大小时,它必须重新计算左值。我该如何修改脚本来实现这一点?用window.resize函数召回scrollContent()函数是一个新手的解决方案。这会给IE带来冲突

您可以将宽度设置为resize,并使函数像这样调用变量。这个方法将你的函数转换成一个js对象,window update重置该对象中的width变量。当然现在你可以这样调用这个函数:scrollContent.scroll();

var scrollContent = {
        width: 0,
        scroll:function(){
            var div = $('#scrolling-content'),
                     ul = $('ul.image'),
                     // unordered list's left margin
                     ulPadding = 0;
            //Get menu width
            scrollContent.width = div.width();
            //Remove scrollbars
            div.css({overflow: 'hidden'});
            //Find last image container
            var lastLi = ul.find('li:last-child');
            //When user move mouse over menu
            div.mousemove(function(e){
            //As images are loaded ul width increases,
            //so we recalculate it each time
            var left = (e.pageX - div.offset().left) * (ulWidth-scrollContent.width) / scrollContent.width;
              div.scrollLeft(left);
            });
        }  
    };
$(window).resize(function() {
        $("#scrolling-content").css("width",$(window).width() + "px");
        $("#scrolling-content").css("height",($(window).height()-400) + "px");
        scrollContent.width = $(window).width();
});

你也可以只声明一个标准的js变量,并使用它来保持事情简单。我更喜欢使用js对象来消除可能的var干扰。