gpt4 book ai didi

javascript - 如何在javascript中重新计算变量

转载 作者:行者123 更新时间:2023-11-28 10:05:57 24 4
gpt4 key购买 nike

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 带来冲突。

最佳答案

您可以设置调整大小的宽度,并使您的函数像这样调用变量。此方法将您的函数转换为 js 对象,并且窗口更新会重置该对象内的宽度变量。当然,现在您可以这样调用该函数: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 var 并使用它来使事情变得简单。我只是更喜欢使用 js 对象来消除可能的 var 干扰。

关于javascript - 如何在javascript中重新计算变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8393006/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com