【发布时间】:2016-07-14 16:26:52
【问题描述】:
我有一个jQuery函数,我只想在浏览器窗口具有最小宽度时执行(该函数是在页面上的内部链接之间上下移动时添加平滑滚动效果,但会干扰菜单我试图在宽度小于最小宽度时进行调整),我几乎可以通过以下几行来获得它,这些行在页面加载和调整窗口大小时执行,当我从次最小宽度传递时效果很好(没有-效果)到超过最小宽度(效果),但不是向后(从效果到无效果)。就像缺少了一些,删除 else 语句中以前的代码或变量的指令,但我不知道是什么。这里是 jQuery 代码:
// the code has 3 detection modes for the width of the browser so it is repeated 3 times
$(window).on("load resize",function(){
if (self.innerWidth > 996) { //first detection mode
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
}
else {
// here some instruction that reset values or something that provoke that
// previous code, loaded when window is > 996 don't be active when window < 996
}
});
$(window).on("load resize",function(){
if (document.documentElement && document.documentElement.clientWidth > 996) { //second detection mode
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
}
else {
// here some instruction that reset values or something that provoke that
// previous code, loaded when window is > 996 don't be active when window < 996
}
});
$(window).on("load resize",function(){
if (document.body > 996) { //third detection mode
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
}
else {
// here some instruction that reset values or something that provoke that
// previous code, loaded when window is > 996 don't be active when window < 996
}
});
为我解决了!
我通过做一些我从一开始就必须做的事情来解决这个问题,但是我暂时的无知(我正在学习)使得当时很难看到。只需我将效果限制在 id="content" 的部分中,并且对所有页面(包括菜单)都没有,我在第一行指定了这一点。
$('#content a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
抱歉,相对浪费了时间,无论如何,我上面定义的内在问题是真实的,我在这个网络上看到其他帖子有一个非常相似的问题;从无活动(小窗口)到活动(大窗口)时效果激活,但从活动(大窗口)到无活动(小窗口)时不去激活,并且没有答案。
【问题讨论】:
标签: jquery resize width smooth-scrolling