click mouse position with scroll in javascript

前端 未结 3 643
感情败类
感情败类 2020-12-19 19:43

I have code to get x-y coordinates when the browser scrolls:

left1 = window.event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
t         


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-19 20:05

    Remember that the click event is handled differently in Mozilla than it is in internet explorer. Also they hold different ways of attaining the position of the cursor location. This is a very easy google search to get the specifics on either.


     var IE = document.all ? true : false; // check to see if you're using IE
    
    if (IE) //do if internet explorer 
            {
                cursorX = event.clientX + document.body.scrollLeft;
                cursorY = event.clientY + document.body.scrollTop;
            }
            else  //do for all other browsers
            {
                cursorX = (window.Event) ? e.pageX : event.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
                cursorY = (window.Event) ? e.pageY : event.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
            }
    

    Also note that you should have something like the following in your initialization code:

    if (window.Event) {
                if (window.captureEvents) { //doesn't run if IE
                    document.captureEvents(Event.MOUSEMOVE);
                }
            }
            document.onmousemove = refreshCursorXY;
    

    On the click side of things as I said there is differences in what value the click is attributed between browsers. For example, this check should happen in your click event (that you send e, the event, to). e will not be sent by I.E. so we do it like so:

    //internet explorer doesn't pass object event, so check it...
            if (e == null) 
            {
                e = window.event;
            }
    
            //1 = internet explorer || 0 = firefox
            if ((e.button == 1 && window.event != null || e.button == 0)) 
    

    And again, there are many differences between IE and other browsers, thus there is much documentation. Google searches can do wonders if you require further information on the subject.

提交回复
热议问题