演示:
http://blackmiaool.com/soa/43093224/
没有人保证不可见的图片会被加载。浏览器有权利选择不预加载您的不可见图片,因此您问题中的 CSS 方法可能在某些浏览器中无效。上面的演示是我自己编写的。它实际上在屏幕上呈现图像,以确保图像已加载。
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>test</title>
</head>
<body>
<h1 style="color:white;text-align:center;">Try to hover</h1>
<div class="show-area"></div>
<link rel="stylesheet" href="style.css">
<script src="../js/jquery.min.js"></script>
<script>
function preloadImage(src, cb) {
const $dom = $("<img />", {
src: src
});
if ($dom[0].naturalWidth) {
cb && cb();
return;
}
$dom.css({
opacity: 0.01,
position: 'fixed',
bottom: 0,
left: 0,
height: 1,
width: 1,
'z-index': 10000,
'pointer-events': 'none',
});
$(document.body).append($dom);
$dom.on("load", function() {
$dom.remove();
cb && cb();
});
}
$("link").each(function() {
const href = $(this).attr("href");
$.get(href, function(style) {
const urls = [];
let match = style.match(/url\([\s\S]+?\)/g);
match.forEach(function(str) {
str = str.replace(/\s/g, "")
.replace(/^url\(/, "")
.replace(/\)$/, "");
let url = str.match(/^["']?([\S]+?)["']?$/);
if (!url || !url[1]) {
console.warn("Can't find url of " + str);
} else {
url = url[1];
preloadImage(url);
}
});
});
});
</script>
</body>
</html>
CSS:
body{
margin: 0;
background-color: black;
}
.show-area {
height: 100px;
width: 300px;
margin: auto;
margin-top: 100px;
background: url( ./1.jpg) no-repeat center;
background-size: contain;
}
.show-area:hover {
background-image: url("./2.jpg ");
}
background
而不是background-image
。请参阅 https://developer.mozilla.org/en-US/docs/Web/CSS/Shorthand_properties#Background_Properties - helb