简体   繁体   中英

Find closest element to click and style it with javascript

I have a loop that generates 200 links and places them randomly on the page. I'm trying to make the closest link change color on a document click event. So If I click white space, the closet link to the click will change color. How can I achieve this given the following code that generates the links:

var links = "<a  class='links'" ;

for (var i=0; i<200; i++)
{
var randomnumber = Math.floor((Math.random()*1001)+1);
document.write(links+"href='#'"+"style="+'"'+"left:"+randomnumber+'px;"'+"id="+i+">links</a><br>");
}

Any broad ideas on how to do this conceptually will be appreciated, in addition to specific code examples. I've explored capturing the clientX and clientY coordinates on click, but then how would I compare in a clear and logical way to the coordinates of all the links and determine the closest one from the click?

*I am not limited to using a loop to generate the links, but I'd like to keep things concise as possible.

Thanks in advance.

Look at this example :)

I'm sorry haven't seen the previous answer when i go to jsfiddle also i'm sorry if it's a bad answer.

 $("div").on('click', function(e) {
       var clkTop = e.pageY - this.offsetTop;
         $("a").each(function() {
               var aTop  = $(this).position().top,
               aLeft = $(this).position().left;

               var d = Math.sqrt((
                  Math.pow(
                      (e.pageX - aLeft), 2) +
                  Math.pow(
                       (e.pageY - aTop), 2) 
               ));

               if (d <= 70 && d >= -70) {
                  $("#putlinktext").text($(this).text());
                   if ($(this).css('color') == 'rgb(255, 0, 0)') {
                          $(this).css('color', 'rgb(0, 255, 255)')
                   } else {
                          $(this).css('color', 'rgb(255, 0, 0)')
                   }
               }
         });
      });

Again i'm sorry for the messy code.

I have created the sample code at fiddle. Using jquery here and its just a barebone. Improve it as per your needs. Please check it..

http://jsfiddle.net/ah7ra/2/
http://jsfiddle.net/ah7ra/

$(document).ready(function() {

    var links = "<span style='display: block; cursor: pointer;' class='linkcont'><a  class='links'" ;

for (var i=0; i<200; i++)
{
var randomnumber = Math.floor((Math.random()*1001)+1);
$('#cont').append(links+"href='#'"+"style="+'"'+"left:"+randomnumber+'px;"'+"id="+i+">links</a></span>");
}

    $('.linkcont').on('click', function() {
        var a = $(this).find('a');
        var id = a.attr('id');
        a.css('color', '#f00');
        alert(id);
    }) ;

});

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