我下载了这个免费的引导程序主题,名为“ Worthy”,我很喜欢它,但是我需要对其进行自定义以供使用。我的意思是制作徽标(标识为“徽标”的img标签),如果您向下滚动最细的部分,则淡入另一张图像。这行得通,但是每次我向下滚动时,它都会“退缩”。这是我制作和使用的jQuery脚本:
jQuery(window).scroll(function() {
if (jQuery(this).scrollTop() > 0) {
$("#logo").fadeOut(function() {
$(this).attr("src", "images/logo2.png").fadeIn();
});
} else {
$("#logo").fadeOut(function() {
$(this).attr("src", "images/logo.png").fadeIn();
});
}
});
这是Dropbox上的站点,如果您想查看的话:https : //www.dropbox.com/sh/1z2sz0hnemshboe/AACjQjFaoG92WTAQJkriIn_Ka?dl=0(徽标只是占位符,呵呵)
因为侦听器scroll
将在每次滚动事件时触发。每次滚动页面。
在您的逻辑中scrolltTop() > 0
,您还应该检查一下是否已经更改了图像。您可以添加类,使用.data()
或src
直接检查。
这是一些示例代码:
jQuery(window).scroll(function() {
// Check if the current logo is set
var isLogo2 = $("#logo").attr("src") === "images/logo2.png";
if (!isLogo2 && jQuery(this).scrollTop() > 0) {
// Change logo if NOT logo 2 and scrolled
$("#logo").fadeOut(function() {
$(this).attr("src", "images/logo2.png").fadeIn();
});
} else if (jQuery(this).scrollTop() == 0) {
// Otherwise, if we're at the top of the page
$("#logo").fadeOut(function() {
$(this).attr("src", "images/logo.png").fadeIn();
});
}
});
注意,这些条件下的逻辑未经测试,但是如果遇到问题,您应该能够进行一些简单的调试。
到底,让我们获得一个有效的代码段示例:
jQuery(window).scroll(function() {
// Check if the current logo is set
var isRed = $("body").hasClass("red");
if (!isRed && jQuery(this).scrollTop() > 0) {
// Change logo if NOT red and scrolled
$("body").addClass("red");
// Add a text to ensure we're not re-applying red
// on EVERY scroll event
$("<div class='alert'>CHANGED TO RED!</div>").appendTo('body').fadeOut(500);
} else if (jQuery(this).scrollTop() === 0) {
// Otherwise, if we're at the top of the page
$("body").removeClass("red");
// Add a text to ensure we're not re-applying red
// on EVERY scroll event
$("<div class='alert'>REMOVED RED!</div>").appendTo('body').fadeOut(500);
}
});
body {
height: 9000px;
background-color: blue;
}
.red {
background-color: red;
}
.alert {
background: #fff;
position: fixed;
}
.css {
position: fixed;
background: green;
top: 20px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="css"></div>
该代码段不适src
用于图像上的属性,但是您应该看到能够将其应用于用例的逻辑。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句