Jquery:当鼠标指针进入和离开元素时,创建一个弹出窗口

Jquery: Create a popup window when the mouse pointer enters and leaves the elements

本文关键字:创建 一个 窗口 鼠标指针 元素 离开 Jquery      更新时间:2024-03-23

当鼠标指针进入和离开元素时,我想在web浏览器的中间创建一个弹出窗口。弹出窗口显示我提供的图像。

我应该如何在Jquery中实现这一点?或者有什么好的插件可以做到这一点吗?

感谢

尝试jQuery UI对话框。

演示

将事件处理程序绑定到mouseout事件。有关更多信息,请参阅链接:http://api.jquery.com/mouseout/

解决这个问题的一种方法是创建一个div(它将容纳您的弹出窗口),并使用隐藏和显示jquery效果。

这很容易,你可以这样做:

$('.hovered_element').mouseenter(function() {
  // you can use some plugin here, or just a simple .show()
  $('.popup_element').show();
  //if you want popup to fade in
  //$('.popup_element').fadein(600);
});
$('.hovered_element').mouseleave(function() {
  // again: any js plugin method, or just .hide()
  $('.popup_element').hide();
  //if you want popup to fade out
  //$('.popup_element').fadeout(600); 
});

当然,你需要设计你的.popup_element,让它出现在中心,或者你喜欢的任何地方。

由于您是编码新手,我建议您使用jQuery团队的jQueryUI库,其中包括.dialog()功能(他们称之为"小部件")。以下是它的工作原理:

(1)<head></head>标记中同时包含jQueryjQueryUI库。请注意,您还必须为jQueryUI包含一个适当的CSS主题库(否则对话框将不可见):

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/flick/jquery-ui.css" />
    <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>

(2)在HTML中创建一个空div,并将其初始化为对话框:

HTML:

<div id="myDlg"></div>

jquery:

$('#myDlg').dialog({
    autoOpen:false,
    modal:true,
    width: 500,
    height: 'auto'
});

(3)然后,当您准备好显示对话框时,在打开对话框之前将新数据插入myDlgdiv:

$('#myDlg').html('<div>This will display in the dialog</div>');
$('#myDlg').dialog('open');

请注意,您可以在html()方法中放入任何HTML,包括一个图像。

上面的代码允许您更改对话框的内容,并每次使用相同的对话框DIV。


以下是工作示例的样子:

jsFiddle演示

HTML:

<div id="myDlg"></div>
<div id="questiona" class="allques">
    <div class="question">What is 2 + 2?</div>
    <div class="answerswer">4</div>
</div>
<div id="questionb" class="allques">
    <div class="question">What is the 12th Imam?</div>
    <div class="answerswer">The totally wacky reason why Iran wants a nuclear bomb.</div>
</div>

jQuery:

var que,ans;
$('#myDlg').dialog({
    autoOpen:false,
    modal:true,
    width: 500,
    height: 'auto',
    buttons: {
        "See Answer": function(){
            $('#myDlg').html(ans);
            $('.ui-dialog-buttonset').next('button').hide();
        },
        "Close": function(){
            $('#myDlg').html('').dialog('close');
        }
    }
});
$('.allques').hover(
    function(){
        //hover-IN
        que = $(this).find('.question').html();
        ans = $(this).find('.answer').html();
        $('#myDlg').html(que).dialog('open');
    },
    function(){
        //hover-OUT -- do nothing
    }

资源:

如何使用弹出插件

http://jqueryui.com/dialog/

http://blog.nemikor.com/2009/04/08/basic-usage-of-the-jquery-ui-dialog/

jQuery UI对话框-关闭后不打开

动态更改jQueryUI对话框按钮

jQuery UI对话框-关闭时的事件出现问题