Hover over 10 pixels

I have a bunch of text with links. I would like to be able to fire an event (some kind of β€œhover” event) when the cursor is less than 10 pixels from the given link. I know I can use padding , but then this will create additional space between the links and the rest of the text.

Is there a good way to do this?

+4
source share
4 answers

you can use this code to see that another answer has flaws, and a new version: http://jsfiddle.net/25gSY/1/

HTML:

 works here <a href="#" style="position:relative"> <span style="position:absolute;top:-20px;left:-20px"></span>example </a> and works here 

JavaScript:

 $('span').width($('span').parent().width()+40); $('span').height($('span').parent().height()+40); $('span').hover(function(){alert('123')}); 
+2
source

if you indent 10px on them, then put -10px margins on them. This should bring you closer to the same view before filling out.

+2
source

This function will work on any element without the need to add markup to your HTML.

Demo: http://jsfiddle.net/ThinkingStiff/Lpg8x/

Script:

 $( 'body' ).mousemove( function( event ) { if( isNear( $( '#your-element' ), 20, event ) ) { //near } else { //not near }; } ); function isNear( $element, distance, event ) { var left = $element.offset().left - distance, top = $element.offset().top - distance, right = left + $element.width() + ( 2 * distance ), bottom = top + $element.height() + ( 2 * distance ), x = event.pageX, y = event.pageY; return ( x > left && x < right && y > top && y < bottom ); }; 
+2
source

Well, this is the javascript version, although I think I would personally use Jared (depending on the context ..)

 $("p").bind("mousemove", function(e) { var links = $("a", this); for(var i = 0 ; i < links.length; i++) { var link = $(links[i]); var linkPosition = link.position(); var linkSize = {width: link.width(), height: link.height()}; var mousePosition = {left: e.pageX, top: e.pageY}; //match top var matchTop = false; if(mousePosition.top >= linkPosition.top - 10 && (mousePosition.top <= linkPosition.top + linkSize.height + 10)) { matchTop = true; } //match left var matchLeft = false; if(mousePosition.left >= linkPosition.left - 10 && (mousePosition.left <= linkPosition.left + linkSize.width + 10)) { matchLeft = true; } if(matchLeft&&matchTop) { link.addClass("HOVER"); } else { link.removeClass("HOVER"); } } }); 
0
source

Source: https://habr.com/ru/post/1380474/


All Articles