简体   繁体   中英

How do I include an element's margin in the hot-spot for jQuery's hover() event?

   jQuery(".my_container").hover(function(){
    //do code
   }, function(){
    //do code
   });

.my_container { width: 100px; height: 100px; margin: 50px; }

The code above doesn't react to mouse over of margin (margin isn't a part of element?) - how can I change that?

You could use a 50px transparent border instead - the margin isn't really supposed to be mouseable...

Include a pseudo element , eg

.my_container:before {
    content:'';
    position:absolute;
    top:-50px;
    bottom:-50px; 
    left:-50px;
    right:-50px; 
}

This adds an extra 50px to the existing element's clickable area.

If you only want to add this on touch screen devices, you could do this:

.touchevents .my_container:before {
    ...
}

This requires something like Modernizer to insert the appropriate feature-based CSS class.


Update

As per @Jaladh's comments, you may also need to apply position:relative to the container element, since position:absolute above will be relative to the first ancestor with a position attribute:

.my_container {
    position:relative;
}

Perhaps use a 2nd wrapper element with padding on the outer element and existing background and padding styles on the inner element:

<div class="my_container">
    <div class="my_container_inner">
        <!-- etc. -->
    </div>
</div>
jQuery(".my_container").hover(function(){
  //do code
}, function(){
  //do code
});
.my_container { padding: 50px; }
.my_container_inner { width: 100px; height: 100px; /* etc. */ }

Building upon @Dunc's solution, you can alternatively use pseudo element to mimic your container and let actual container behave like margins . This will look like:

.my_container { 
    width: calc(100px + (2 * 50px));
    height: calc(100px + (2* 50px));

    position: relative;
}

.my_container::before {
    content: '';
    position: absolute;
    top: 50px;
    bottom: 50px; 
    left: 50px;
    right: 50px; 
}

Also make sure to move all other properties (like background color, border, etc.) you had in my_container to my_container::before because before is acting like our container here.

This is essentially helpful if your containers are grid items and you want gaps in-between them to be hoverable , because otherwise using psuedo element to add margins won't work appropriately in that case.

Change the margin to padding and it'll be hoverable.

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