Clickable after pseudo-element

demonstration

JQuery

$('#main:after').click(function(e){ e.preventDefault(); $('#main').hide(); }); 

CSS

 #main{ background-color: red; width: 100%; height: 200px; } #main:after{ position: absolute; bottom: 200px; background-color: blue; width: 20px; height: 20px; content: " "; } 

How to hide a red div when clicking on a blue div?

+4
source share
1 answer

UPDATE

I had a little game and believe that I came up with something that solves this problem for the source code.

Essentially, I assigned the same :after CSS to the dummy class, and then create and destroy the element with the dummy on the fly. Between creation and destruction, we can get the necessary dimensions (width, height, positioning). Finally, we can compare these values ​​with the coordinates of the clicks ...

DEMO: http://jsfiddle.net/gvee/gNDCV/6/

CSS

 #main { background-color: red; width: 100%; height: 200px; position: relative; } #main:after, .mainafter { position: absolute; bottom: -100px; right: 50%; background-color: blue; width: 40%; height: 20px; content:" "; } 

JQuery

 $('#main').click(function (e) { var pseudoElement = $('<div></div>').addClass('mainafter'); $(this).append(pseudoElement); var w = pseudoElement.width(); var h = pseudoElement.height(); var x = pseudoElement.position().left; var y = pseudoElement.position().top; pseudoElement.remove(); if (e.pageY - $(this).position().top > y && e.pageY - $(this).position().top < y + h && e.pageX - $(this).position().left > x && e.pageX - $(this).position().left < x + w ) { alert('Not red'); } }); 

If the expression is:

Illustration of if statement

PageX is the horizontal coordinate of the cursor. X is the coordinate of the left edge of the blue square. W is the width of the blue square.

Therefore, we can work out the right side of the blue rectangle by simply adding: X+W

The same logic can be applied to vertical coordinates (top = Y, bottom = Y + H).

The if in our jQuery above checks if PageX between the left and right edges of the blue field and that PageY is between the top and bottom. that is, the cursor in the blue box!


There is a [kludgy] workaround to your provided code (where the content :after is located below its container) ...

Develop a mouse click coordinate and see if it exceeds the size of the #main div section ...

DEMO: http://jsfiddle.net/gvee/gNDCV/3/

CSS

 #main { background-color: red; width: 100%; height: 200px; position: relative; margin-bottom: 20px; /* to clear content:after */ } #main:after { position: absolute; bottom: -20px; /* -(this.height) */ background-color: blue; width: 20px; height: 20px; content:" "; } 

JQuery

 $('#main').click(function (e) { if (e.pageY - $(this).offset().top > $(this).height()) { alert('Not red'); } }); 
+4
source

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


All Articles