我有一个适用于台式机、平板电脑和移动设备的网站。使用桌面,我网站上的图像很大。使用平板电脑,这些相同的图像会被调整大小。再次使用移动设备,这些相同的图像会再次调整大小。我正在使用加载到桌面移动设备上的相同图像。这对移动设备来说是糟糕的表现。我想要的是替换那些图像,并显示这些图像的缩略图。
注意:图像是使用 PHP for 循环从我的数据库中检索的。
我能做什么:
jQuery:
$(document).ready(function() {
// run test on initial page load
checkSize();
// run test on resize of the window
$(window).resize(checkSize);
});
//Function to the css rule
function checkSize(){
if ($(".sampleClass").css("float") == "none" ){
// replaces images code here
}
}
CSS:
.sampleClass {float:left;}
@media only screen and (max-width: 800px){
.sampleClass {float:none;}
}
我假设这段代码将加载大图像,然后加载缩略图。因此,创造了更糟糕的体验。我怎样才能使图像在移动设备上自动替换为缩略图,而无需加载大型桌面图像?
最佳答案
HTML
<div class="bgDiv" data-desktop-image="desktop.png" data-tablet-image="Tablet.png" data-mobile-image="Mobile.png"></div>
脚本
function checkSize() {
var windowWidth = $(window).width();
$Element = $('.bgDiv');
if (windowWidth > 1024) {
currentImage = $Element.attr('data-desktop-image');
} else if (windowWidth > 767 && windowWidth < 1025) {
currentImage = $Element.attr('data-tablet-image');
} else {
currentImage = $Element.attr('data-mobile-image');
}
$Element.css('background-image', 'url(' + currentImage + ')');
}
关于javascript - 用 jQuery 替换图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38519019/