我有以下代码:
var logo1 = "//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_2x.png";
var logo2 = "//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_hover_2x.png";
var images = new Array (logo1, logo2);
var index = 1;
function rotateImage()
{
$('.logoimage').fadeOut('fast', function()
{
$(this).attr('src', images[index]);
$(this).fadeIn('fast', function()
{
if (index == images.length-1)
{
index = 0;
}
else
{
index++;
}
});
});
}
$(document).ready(function()
{
setInterval (rotateImage, 5000);
});
var images = new Array (logo2);
var index = 1;
function rotateImage()
{
$('.logoimage').fadeOut('fast', function()
{
$(this).attr('src', images[index]);
$(this).fadeIn('fast', function()
{
if (index == images.length-1)
{
index = 0;
}
else
{
index++;
}
});
});
}
$(document).ready(function()
{
setInterval (rotateImage, 5000);
});

除了以下错误之外,它的运行良好: 即使图像已在页面上显示,图像也会加载。 我对该图像有一个图像onmousehover效果,并导致不良影响。
是否可以在图像src和img onmousehover src之间进行交换? 谢谢 亚历
答案 0 :(得分:1)
您可以使用JavaScript更改img标记的src
,如下所示
function hover(element) {
element.setAttribute('src', '//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_2x.png');
}
function unhover(element) {
element.setAttribute('src', '//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_hover_2x.png');
}
和html是
<img id="my-img" src="http://dummyimage.com/100x100/000/fff" onmouseover="hover(this);" onmouseout="unhover(this);" />
编辑后:
如果您想在某些timeout
上进行更改,则需要将以下代码放在window.onload = function() {}
var images = new Array();
images[0] = "logo_1.png";
images[1] = "logo_2.png";
var images = new Array();
for (var i = 0; i < 2; i++) {
images.push("logo_" + i + ".png");
}
var x = 0;
function changeImage() {
document.getElementById('ad').src = images[x];
if (x < 8) {
x += 1;
} else {
x = 0;
}
if (window.addEventListener) {
window.addEventListener('load', changeImg, false);
}
function changeImg() {
var x = 0;
setInterval(function() {
changeImage()
},5000);
}
HTML:
<img id="ad" src="//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_2x.png" />
答案 1 :(得分:1)
使用jQuery hover在悬停进出元素时运行代码。也可以使用setTimeout在延迟后运行代码。
var logo1 = "//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_2x.png";
var logo2 = "//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_hover_2x.png";
$(function() {
$('.logoimage').hover(function() {
setTimeout(function() {
$('.logoimage').attr('src', logo2);
}, 1000);
}, function() {
setTimeout(function() {
$('.logoimage').attr('src', logo1);
}, 1000);
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img class="logoimage" src="//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_2x.png">
&#13;