简体   繁体   中英

jQuery: how to place a highlight to cover another element?

I want to create a transparent highlight to cover a particular DOM element.

My highlight will occasionally be switched from one element to another.

The basic implementation is easy: create an empty <div class='highlight'/> with css attributes for background-color and opacity.

But having it follow another element seems hard, because the highlighted element could move or resize or show or hide, and I'm not sure how to have the highlight follow it.

There must be someone who's done this before -- Firebug seems to have the effect I want, but I don't know how to delve into the Firebug source code + find the relevant piece.

Any suggestions?

有什么原因不能使用jQuery高亮效果

Simple HTML element at the top of your DOM:

<div id="highlighter" class="highlight"></div>

Style it with abstracted CSS:

div {
    border:1px solid #CCC;
    position:relative;
}
#highlighter {
    display:none;
    border:none;
}
.highlight {
    z-index:999999;
    background-color:yellow;
    opacity:.5;
    -moz-opacity:.5;
    position:absolute;
    width:100%;
    height:100%;
}

The JQuery is a little more complicated if you want the highlighter to tag along with your animated divs:

$('div').not('.highlight').on('click', function() {
    var $this = $(this);
    if($this.find('.highlight').length > 0) {
        $this.find('.highlight').remove();
    } else {
        $('#highlighter').clone().appendTo($this).
        width($this.width()).
        height($this.height()).
        css({
            'top': '0px',
            'left': '0px'
        }).
        show();
    }
});


(function morph(){

    $('div').not('.highlight').each(function(){
        var $this = $(this);
        $this.animate({
            'top'  : someVal + 'px',
            'left' : someVal + 'px',
            'width': someVal + 'px',
            'left' : someVal + 'px',
        }, {
            duration: 1000,
            step: function(){
               // Here we tell the highlighter to sync up with the morphed parent.
               $this.find('.highlight').width($this.width()).height($this.height());
            },
            complete: morph
        });
    });
}());

Demo: http://jsfiddle.net/AlienWebguy/7t4jT/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM