我正在尝试根据屏幕尺寸更改图像 src。
$(document).ready(function() {
$(function() {
if($(window).width() < 568) {
$("#crewimage").each(function() {
$(this).attr("src", $(this).attr("src").replace("resources/images/thecrew.png", "resources/images/thecrewmobile.png"));
});
} else if ($(window).width() >= 568) {
$("#crewimage").each(function() {
$(this).attr("src", $(this).attr("src").replace("resources/images/thecrewmobile.png", "resources/images/thecrew.png"));
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="crew-content">
<img id="crewimage" src="resources/images/thecrew.png" alt="Header Image"></img>
</div>
我的逻辑似乎很可靠。我不确定为什么它不起作用。
提前感谢您的帮助。
最佳答案
你需要使用jquery的resize
函数。
工作 fiddle :https://jsfiddle.net/f0ngoLkq/1/
HTML
<div id="crew-content">
<img id="crewimage" src="http://completewebgraphics.com/wp-content/uploads/2015/11/Mobile-Apps-Development-in-India.jpg" alt="Header Image" />
</div>
jQuery 代码
$(window).resize(function(e){
if($(window).width() < 568) {
console.log($(window).width());
$("#crewimage").each(function() {
$(this).attr("src", "http://s3.amazonaws.com/libapps/customers/1633/images/icon_52143.png");
});
} else if ($(window).width() >= 568) {
$("#crewimage").each(function() {
$(this).attr("src","https://ithemes.com/wp-content/uploads/2012/07/mobile300.png");
});
}
});
希望这对您有所帮助!
关于javascript - 使用 Jquery 替换基于屏幕大小的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39631607/