问题描述
|
我有两个div叠放在一起,当鼠标悬停在div上时,我的代码会展开框。当您从div中删除鼠标时,div会缩小到原始大小。
当您将鼠标滑入div,然后从div中滑出到页面的空白区域时,我的代码工作得很好而且很花哨。但是,如果您尝试在两个div之间移动鼠标,一切将变得一团糟,现在正确的框不再缩小并且整体功能会丢失。
这是我的代码:
$(\".divBox1\").hover(function() {
var height = $(this).height();
var height2 = $(this)[0].scrollHeight;
if (height2 > 35) {
//Current position in relation to the page
var offsetTop = $(this).offset().top;
var offsetLeft = $(this).offset().left;
//Clone the code and attach it to the page
$(this).clone().css({
position: \"absolute\",top: offsetTop,left: offsetLeft
}).attr(\"id\",\"cloned\").appendTo(\"body\");
//Hide the code underneath
//$(this).css(\"visibility\",\"hidden\");
$(\'#cloned\').animate({
height: height2
},150).bind(\'mouseleave\',function() {
var cloned = $(this);
//Animate back and remove
cloned.animate({
height: height
},300,function() {
cloned.remove();
//Show the code underneath
//$(this).css(\"visibility\",\"visible\");
});
});
}
});
这是我关联的HTML和CSS
.divBox1 {
color: #100;
background-color: #f9f9f9;
border: 1px solid silver;
overflow: hidden;
width: 200px;
height:35px;
}
<div class=\"divBox1\" id=\"one\">
sdsdsadasdsad<br />
sadasdsdaasdadsadssdsdsadasasdasdsdsddsasdasdasdasdasddasadsasd<br>
dasdasasdasdsad
<br /><br />
Really Tall Box!
</div>
<br />
<div class=\"divBox1\" id=\"two\">
Second Box<br />
yada ydad<br />
yada yada<br />
yada yada<br />
</div>
对于那些感兴趣的人,该项目也位于Jsfiddle上:http://jsfiddle.net/hQkFH/10/
另外,如果有人想知道为什么我在动画前就克隆了该框,这是因为我要打开框来覆盖它下面的页面上的任何内容(对于顶部框,第二个框)
谢谢!
解决方法
在克隆divbox之前,您是否尝试过添加
$(\'#cloned\').remove();
?
我认为问题在于,当您同时输入两个悬停事件时,您最终会获得两个id为“ cloned \”的div
, 当用户进入第一个div而第二个仍是动画时(因此页面中已经有一个\'cloned \'元素),就会发生此问题。
这是使用animation
变量(布尔值)的解决方法:http://jsfiddle.net/hQkFH/14/
它修复了该错误,但是当用户在第一个div仍处于动画状态时进入第一个div时,它什么也不做(但是,如果他再次回到第一个div,它将正常打开)
, 使用.stop(true,true)
清除动画队列。