我有一张带有缩略图的照片幻灯片。下一步/上一步按钮的显示和消失取决于窗口的大小;如果缩略图超出窗口大小,则会显示按钮。如果没有,它们就会消失。我的问题是,有时,他们不会出现,或者他们不会出现几秒钟。在其他时候,它们不会消失。有时它工作得很好。
对于jQuery和JavaScript,我还是个新手。有什么建议吗?
// hide previous and next buttons
$('#prev, #next').hide();
// get width of thumbnail list
var thumbsWidth = $('div#thumbs ul').width();
// show/hide next/prev buttons
function buttonVisibility() {
if (thumbsWidth + 225 > screenWidth) {
$('#prev, #next')
.fadeTo('fast', 0.5)
.hover(function(){
$(this).fadeTo('fast', 1);
}, function(){
$(this).fadeTo('fast', 0.5);
});
} else {
$('#prev, #next').fadeTo('fast', 0, function(){
$(this).hide();
});
}
}
// declare global screenWidth variable
var screenWidth
// find width of thumbnail window and show/hide next/prev buttons accordingly
function findWidth(){
screenWidth = $('div#thumbs').width();
buttonVisibility();
}
// perform findWidth() on load and on window resize
findWidth();
$(window).resize(function(){
findWidth();
});发布于 2010-07-13 00:59:28
这可能是浏览器在调整窗口大小(即根据窗口大小的变化重新设计布局)时固有的工作,再加上您正在进行的DOM更改,只是使事情停滞不前。您可以尝试在触发代码之前等待用户交互完成。
$(window).resize((function() {
var timeout = null;
return function() {
if (timeout) clearTimeout(timeout);
timeout = setTimeout(findWidth, 250);
};
})());这将改变事情,使您的代码不会尝试做任何事情,直到用户暂停或停止拖动窗口后的1/4秒。
发布于 2010-07-13 00:54:13
加载时计算一次screenWidth,因此您不必反复搜索div#thumbs。
发布于 2010-07-13 00:59:05
创建一个变量displayed,该变量存储按钮是否可见的当前状态。现在,在resize事件中,仅当它们被隐藏时才执行fadeIn。
您还可以存储所选元素,以避免每次都进行选择。
// hide previous and next buttons
$prevNext = $('#prev, #next');
$prevNext.hide();
// get width of thumbnail list
var $thumbs = $('#thumbs');
var thumbsWidth = $('#thumbs ul').width();
var screenWidth;
var displayed = false;
// show/hide next/prev buttons
function buttonVisibility() {
if (thumbsWidth + 225 > screenWidth) {
if (!displayed) {
displayed = true;
$prevNext.fadeTo('fast', 0.5).hover(function () {
$(this).fadeTo('fast', 1);
}, function () {
$(this).fadeTo('fast', 0.5);
});
}
} else if (displayed) {
displayed = false;
$prevNext.fadeTo('fast', 0, function () {
$(this).hide();
});
}
}
// find width of thumbnail window and show/hide next/prev buttons accordingly
function findWidth() {
screenWidth = $thumbs.width();
buttonVisibility();
}
// perform findWidth() on load and on window resize
findWidth();
$(window).resize(findWidth);
https://stackoverflow.com/questions/3230359
复制相似问题