每当我将鼠标悬停在任何图像上时,我都必须创建一个窗口。约束是窗口已定义且不应重复。意味着,如果我有 10 个图像,而不是 10 个类似的窗口,则只有 1 个窗口应该动态更改其宽度、高度和位置(左、右、上、下)以充当图像的边框。边框效果可以使用 CSS 获得,但我还有其他要求,需要这种动态边框效果。
<div> <!-- This is the border div -->
<div id="top" class="imageBorder" style="display: block; width: 105px">Top</div>
<div id="left" class="imageBorder" style="display: block; width: 105px"></div>
<div id="right" class="imageBorder" style="display: block; width: 105px"></div>
<div id="bottom" class="imageBorder" style="display: block; width: 105px">Bottom</div>
</div>
上面的 div 用作窗口。每当我将鼠标悬停在任何图像上时,这个 div 应该包围它。我不希望一次复制此 div 并将其关联到每个图像。
最佳答案
如果图像不是缩略图并且尺寸不同,那么您可以根据所选/事件图像的宽度和高度动态设置单个容器的宽度和高度。
HTML:
<div id="container"></div>
<img class="img" src="http://www.so.com/390px-Amtgard-300x200.jpg" />
<img class="img" src="http://www.so.com/390px-Amtgard-300x200.jpg" />
<img class="img" src="http://www.so.com/390px-Amtgard-300x200.jpg" />
CSS
#container{
position: absolute;
width: 100px;
height: 100px;
background-color: red;
z-index: 2;
display:none;
}
.img{max-width: 80px; max-height: 80px; z-index: 10000;}
JS/jQuery
$(document).ready(function(){
$(".img").hover(function(){
//on mouseenter
var img = $(this);
img.addClass("this");
var c = $("#container");
//change container width/height based on image size
c.css({width:img.outerWidth() + 20, height: img.outerHeight + 10});
//position container
c.css({top:img.offset().top - 10, left: img.offset().left - 10, position:'absolute'}).fadeIn("fast");
//reset other images z-index
$(".img:not(.this)").css("zIndex","1");
}, function(){
//on mouseleave
if(!$("#container").css("display","none"))
$("#container").fadeOut("fast");
$(".img").css("zIndex","4");
$(this).removeClass("this");
});
});
说明
jQuery 是最强大的 javascript 库,我建议您学习如何专门使用它,因为它将提高您的 javascript 技能并提高您的 UI 技能。通常我使用类和 ids 定义 html 元素,这样我就可以利用 javascript/jQuery。
.悬停
我正在使用 .hover
事件处理程序,详细说明 here 。使用此事件处理程序,您可以使用单个处理程序定义 mouseenter
和 mouseleave
,因为第一个匿名函数处理 mouseenter
而第二个匿名函数处理 鼠标离开
。
.css
这个 jQuery 方法允许您对 html 的 css 进行几乎任何您想要的操作。
注意:outerWidth()、outerHeight() 或 width()、height() 将产生不同的结果。使用哪一个取决于元素是否具有 box-sizing:border-box
或 border
。
.css("zIndex", "4")
这是 jQuery 动态编辑 css z-index
的方式。这就是 #container
能够重叠其他不活动图像的方式。
$(这个)
当您将事件处理程序(我建议您学习如何尽可能多地使用)与 css 类一起使用时,$(this)
变得非常宝贵。这允许您将元素与事件处理程序内的类隔离。
.addClass("这个")
addClass()
和 removeClass()
是改善用户体验的方法。
我经常将其与 hidden
和 disabled
一起使用,其中我需要禁用按钮或隐藏它们等。
.not("这个)
这是一种快速而简单的方法,可以将元素隔离的时间长于事件处理程序在范围内的时间。我在下拉列表(又名选择列表)中经常使用这个。
fadeIn('慢'), fadeOut('快')
将此 jQuery 方法与任何具有以下属性的 html 元素结合使用:display: none
。它允许您切换元素是否可见,这是对 display: none - block 或 inline
结束
在事件处理方面,您必须熟悉的一件事就是传播!在处理事件时,事件监听器将根据以下内容监听事件:
A:事件类型 即: on('click')、on('submit')、on('mouseenter')、on('change') 等...
和
B:元素的类型 即:类或 html 元素(即:div、input、select、a、button 等...)
这可能会导致错误的结果,尤其是在动态创建元素的情况下。
熟悉事件传播、事件冒泡和事件闭包!
关于jquery - 使用 JQuery 在悬停时用 div 包裹图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41196530/