javascript - jQuery 鼠标悬停事件正在复制

标签 javascript jquery html css iframe

我对这个很陌生。我正在尝试通过悬停(鼠标悬停)事件触发的 iFrame 触发链接预览。

这是我目前拥有的 JSFiddle:https://jsfiddle.net/80so5jyL/

它第一次工作正常,但当我多次在链接上来回悬停时,它会重复显示。如何确保每次只弹出一个 iFrame?

我尝试取消绑定(bind) mouseover/mouseout 事件(注释行),它可以防止重复问题,但也不允许我再次显示在同一个链接上,即使在我悬停或悬停之后一个不同的链接(它仍然允许我这样做)。

HTML:

<a class="tester" href="http://therainforestsite.com">Link Uno</a>
<a class="tester" href="http://www.example.com">Link Dos</a>

CSS:

.tester { display: block;
margin: 50px;

}`

JS(jQuery):

$("a").mouseover(function() {
    var thisURL = $(this).attr('href');
    console.log(thisURL);
    var theCode = '<style>.preview {display:none;position:absolute;margin-left:0px;z-index:10;border:1px;solid #000;width:100px;height:100px;}</style><iframe class="preview" src="' + thisURL + '"></iframe>';
    $(this).append(theCode);
    $(this).children(".preview").show();
}).mouseout(function() {
    $(this).children(".preview").hide();
    //$(this).unbind('mouseover');
    return;
});

有什么想法吗?

最佳答案

它的发生是因为你每次都将它附加到 this 上,因此它会被复制。使用 .html 代替,也不要将它放在 this 内,即当您使用 htmla 标签。将它放在一个单独的元素中,因为当您使用.html时,它将替换内容和a标签text会消失的。

所以我建议使用下面的html

<a href="http://therainforestsite.com">Some Link</a><br/><br/>
<a href="http://www.example.com">Example Link</a>
<p class="bigPreview"></p>

CSS

.bigPreview{
   display:none
}

JS

$("a").mouseover(function() {
    var thisURL = $(this).attr('href');
    var theCode = '<style>.preview {display:none;position:absolute;margin-left:0px;z-index:10;border:1px;solid #000;width:100px;height:100px;}</style><iframe class="preview" src="' + thisURL + '"></iframe>';
    $('.bigPreview').html(theCode).show(); //put it into .bigPreview and use .show on it
}).mouseout(function() {
    $('.bigPreview').html('').hide(); //clear its html and hide it
});

关于javascript - jQuery 鼠标悬停事件正在复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34014295/

相关文章:

javascript - (CSS/jQuery) 如何使用 jQuery 解决 top 和 bottom 属性之间的冲突

javascript - 关闭 Nightwatch 中的打印对话框?

javascript - $(this) 和 find 在 JQuery 中不起作用

php - php或javascript或jquery中两个日期之间的差异

javascript - React - IE11 - 访问过的链接在刷新时未被识别为访问过

html - 如何在 Bootstrap 中将以下导航栏居中?

javascript - 为什么 JQuery .animate() 不能按预期工作?

javascript - AngularJS : ng-model doesn't update correctly with ng-keydown. ng-model 关闭一个字符

javascript - Aurelia click.delegate 或 click.trigger 在克隆元素中不起作用

javascript - iOS UiWebView/页面可见性 API : "pageshow" event not firing