0

我的网站上有一个按钮,我想用它来打开和关闭描述框。因此,当单击按钮时,我希望它在您将鼠标悬停在页面上的某些元素上时显示图像预览,但是当取消选择按钮时,它不应该显示任何图像预览。

我创建了一个 jQuery 函数,并根据图像预览窗口是否应该显示给它传递一个布尔值。但是,无论布尔值如何,似乎都在调用悬停函数( $(".node").hover(function(e)) 。我做错了什么?

$('.textIcon').click(function(){

        if(textCount %2 == 0){
                        // show preview images
            imagePreview("true");
            textCount++;
        }
        else{
            // hide preview images
            imagePreview("false");
            textCount++;
        }
    });

jQuery脚本:

<script> 
// create pop up preview box for each step when text labels are off
this.imagePreview = function(on){

    console.log("in imagePreview, on: " + on);  

    /* CONFIG */    
        xOffset = 50;
        yOffset = 140;

        // these 2 variable determine popup's distance from the cursor
        // you might want to adjust to get the right result

    /* END CONFIG */

    if(on=="true"){
        console.log("ON");
        $(".node").hover(function(e){
            console.log("node hover");
            // title of step
            this.t = $(this).data('title');
            this.title = "";
            // image url of step
            this.href = $(this).data('image');
            // show title + image for preview
            if(this.href != null){
                var c = (this.t != "") ? this.t + "<br>": "";
                $("body").append("<p id='preview'>" + c + "<img src='"+ this.href +"' alt='Image preview' style='margin-top:5px' />" +"</p>");  
            }
            // just show title for preview
            else{
                var c = (this.t != "") ? this.t : "";
                $("body").append("<p id='preview'>"+ c +"</p>");    
            }

            $("#preview")
                .css("top",(e.pageY - xOffset) + "px")
                .css("left",(e.pageX + yOffset) + "px")
                .fadeIn("fast");                        

        },
        function(){
            this.title = this.t;    
            $("#preview").remove();
        }); 

        $(".node").mousemove(function(e){
            var dotPosition = $(this).position();
            $("#preview")
                .css("top",(dotPosition.top + xOffset) + "px")
                .css("left",(dotPosition.left + yOffset) + "px");
        }); 
        }
};
</script>
4

1 回答 1

1

每次调用 imagepreview() 时,您都在为悬停事件分配一个函数,而不是尝试分配一次悬停事件并在内部检查它是否应该显示预览。

尝试类似:

var showOnHover = false; // determines behaviour

$('.textIcon').click(function(){ showOnHover = !showOnHover;  }); // change behaviour onclick

// we assign it once
$(".node").hover(function(e){
   // we look if we need to do something now
   if (showOnHover){
       // onHover activated
       // do your stuff
   }
   // else shouldn't show
});
于 2013-02-10T21:03:04.640 回答