我正在处理第215页的jquery Missing Manual(O'Reilly)教程。
给定此 HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Rollover Images</title>
<link href="../_css/site.css" rel="stylesheet">
<style>
#gallery img {
display: inline-block;
margin: 10px;
border: 1px solid rgb(0,0,0);
}
</style>
<script src="../_js/jquery.min.js"></script>
<script src="my_scripts/rollover.js"></script>
</head>
<body>
<div class="wrapper">
<header>
JAVASCRIPT <span class="amp">&</span> jQUERY: THE MISSING MANUAL
</header>
<div class="content">
<div class="main">
<h1>Rollover Images</h1>
<p>Mouse over the images below</p>
<div id="gallery"> <a href="../_images/large/blue.jpg"><img src="../_images/small/blue.jpg" width="70" height="70" alt="blue"></a> <a href="../_images/large/green.jpg"><img src="../_images/small/green.jpg" width="70" height="70" alt="green"></a> <a href="../_images/large/orange.jpg"><img src="../_images/small/orange.jpg" width="70" height="70" alt="orange"></a> <a href="../_images/large/purple.jpg"><img src="../_images/small/purple.jpg" width="70" height="70" alt="purple"></a> <a href="../_images/large/red.jpg"><img src="../_images/small/red.jpg" width="70" height="70" alt="red"></a> <a href="../_images/large/yellow.jpg"><img src="../_images/small/yellow.jpg" width="70" height="70" alt="yellow"></a></div>
</div>
</div>
<footer>
<p>JavaScript & jQuery: The Missing Manual, 3rd Edition, by <a href="http://sawmac.com/">David McFarland</a>. Published by <a href="http://oreilly.com/">O'Reilly Media, Inc</a>.</p>
</footer>
</div>
</body>
</html>
本教程要求我将"大"图像滚动到页面最初加载时显示的小图像上。本书继续使用正则表达式技巧完成上述任务。
我不想以建议的方式完成本教程,我试图弄清楚如何通过仅使用悬停函数中的 replaceWith 函数来正确执行图像翻转。
我想到了这个脚本(翻转.js):
$(document).ready(function() {
$('#gallery a').each(function(){
if ("$(this)[href*='large']" ){
$('<img>').attr('src',$(this).attr('href'));
}
});
$('#gallery img').each(function(){
var $oldimage = 0;
$(this).hover(
function(){
$oldimage = $(this).replaceWith('<img src=' + $(this).parent().attr('href') + '>');
console.log('old image' + $oldimage);
}
,
function(){
$(this).replaceWith('$oldimage');
console.log('comeback' + $oldimage);
});
});
}); // end ready
结果是悬停函数的第一部分(mousenter)被正确执行,但悬停函数的第二部分(mouseleave)似乎根本没有被执行,即使是控制台.log。
该问题是由您在第一个处理程序中执行的操作引起的。在使用 replaceWith
时,您正在更改 DOM(特别是您已将悬停事件绑定到的 img 元素)并影响事件绑定。
您应该使用 attr
函数来更新图像 src 属性,而不是使用 replaceWith
。
编辑
试试这个,例如:http://jsfiddle.net/3dr7n8b7/1/
试试这个:
$(document).ready(function() {
$('#gallery a').each(function(){
if ("$(this)[href*='large']" ){
$('<img>').attr('src',$(this).attr('href'));
}
});
$('#gallery img').each(function(){
var $oldimage = 0;
$(this).on('mouseover',
function(){
console.log($(this));
$oldimage = $(this).attr('src');
$(this).replaceWith('<img src=' + $(this).parent().attr('href') + '>');
// $('#gallery img').each(function(){
$(this).on( "mouseleave", function(){
$(this).replaceWith('<img src=' + $oldimage + '>');
console.log('comeback' + $oldimage);
});
// });
console.log('old image' + $oldimage);
});
});
}); // end ready