如何使用jQuery显示HTML元素?

时间:2012-07-30 00:23:22

标签: javascript jquery

我在这里有一些代码,当你将鼠标悬停在另一个元素上时,它会在1个元素上更改display: nonedisplay: block

HTML:

<li onmouseover="popup('Ipsum');">Lorem</li>

使用Javascript:

$(document).ready(function(){
    $("body").append('<div id="pup"></div>'); // Appends a popup div to the page
    $(document).mousemove(function(e){
        var x,y;                                   // This sets the mouse
                                                   // coordinates into 2
        x = $(document).scrollLeft() + e.clientX;  // variables in order to
        y = $(document).scrollTop() + e.clientY;   // display the tooltip
    });                                            // relative to mouse postition

    function popup(text)
    {
        $('#pup').html(text);  // This is supposed to enter text into the tooltip
        $('#pup').show();      // div and change it from display: none to
                               // display: block
    }

目前,div存在(但是你无法看到它,因为它在CSS中被设置为display: none,但当你鼠标悬停在它上面时它没有显示。谢谢!< / p>

1 个答案:

答案 0 :(得分:1)

我是第二个Russ C的评论。将弹出窗口移出$(document).ready,但不是全局函数。将其指定为匿名函数并将jQuery作为参数。

不知道你想要鼠标事件的帮助。这个出现在鼠标下方。 “title”属性只能包含纯文本,所以如果你想要的东西不那么健壮,那就去吧。

试试这个

    $(document).ready(function(){
        var loremHTML = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. <a href=''>Vivamus non elit risus</a>, a dignissim ligula."
        $("#lorem").hover(function() {$.popup(loremHTML)},function() {$("#pup").hide().remove()});
        $(document).mousemove(function(ev) {
            $.mousePos = {      //Assign mousePos to the jQuery object
                x: ev.pageX,    //x coordinate
                y: ev.pageY     //y coordinate
            };
        });
     });   

     (function($) {
        $.popup = $.fn.popup = function(text) {
            $("body").append('<div id="pup"></div>');
            $('#pup').show().css({
                "position":"absolute",
                "left":$.mousePos.x,
                "top":$.mousePos.y})
                .html(text);
        }
     })(jQuery);

CSS

        #pup {
            background:#ddd;
            padding:5px;
            width:20%;
        }

HTML

<span id="lorem">Lorem</span>