我有一个带有图像的轮播,我想根据窗口宽度将src属性值替换为其他data-src属性值。
<div id="mainCarousel">
<img class="img-carousel" src="img/carousel-main-img2.jpg" data-src="img/carousel-main-datasrc-1.jpg" data-srctwo="img/carousel-main-datasrctwo-1.jpg">
<img class="img-carousel" src="img/carousel-main-img3.jpg" data-src="img/carousel-main-datasrc-2.jpg" data-srctwo="img/carousel-main-datasrctwo-2.jpg">
function carouselImages() {
// set window width in a variable
var winWidth = $(window).width();
// set img DOM element in a variable
var imgCarousel = $('#mainCarousel .img-carousel');
// declare empty variable for img 'data-src' attribute
var dataSrc = $();
// declare empty variable for img 'data-srcTwo' attribute
var dataSrcTwo = $();
//set loop which will iterate on each img DOM element
for(var i=0; i<imgCarousel.length; i++) {
// set first width range condition
if(winWidth > 400 && winWidth < 768) {
// if width matches condition, store the value of each DOM element's 'data-src' attribute in previously declared variable
dataSrc = imgCarousel[i].attr('data-src');
// replace DOM element's 'src' attribute's value with 'data-src' attribute's value
imgCarousel[i].attr('src', dataSrc);
}
// set second width range condition
else if (winWidth >= 768) {
// if width matches condition, store the value of each DOM element's 'data-src' attribute in previously declared variable
dataSrcTwo = imgCarousel[i].attr('data-srcTwo');
// replace DOM element's 'src' attribute's value with 'data-src' attribute's value
imgCarousel[i].attr('src', dataSrcTwo);
}
}
};
$(document).ready(function(){
carouselImages();
});
$(window).resize(function () {
carouselImages();
});
我想实现的是图像src
值获得与替换data-src
值当窗口宽度为401px和767px之间,并与data-srctwo
值当窗口宽度>= 768px
。
在构造函数时,我尝试尽可能地合乎逻辑。但这是行不通的。缩小屏幕和刷新时,或者直接调整浏览器窗口的大小时,src属性值都不会改变。另外,我收到以下错误消息
imgCarousel [i] .attr不是函数
有人能告诉我我的功能背后的逻辑到底出了什么问题吗?以及为什么收到错误消息的原因,因为我认为您不一定需要在条件中包含一个函数。
var imgCarousel = $('#mainCarousel .img-carousel');
是匹配元素的数组。它只是DOM元素,而不是jquery对象。因此,在循环并应用attr
它时将引发错误。
您需要先将其转换为jquery对象,然后再对其应用.attr
方法。
您可以通过以下两种方式之一来引用当前元素
$(imgCarousel[i]).attr('data-src');
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句