简体   繁体   中英

JavaScript keep focus for mousemove when mouse goes over child

I'm making a calendar application and I want to have a bar that goes across the whole thing and whenever you move the mouse, the bar will move with the mouse and tell you what time the bar represents. This works fine, however, when mousing over an event on the calendar, which is a dynamically created div , the bar gets stuck in whatever position it was in when the mouse entered the child div for that calendar event.

I have the seven days of the week as separate divs and use the class calendar-part to be able to call all of them for this jQuery function:

              $(".calendar-part").mousemove(function(e){
                    var y = e.clientY;
                    var x = e.clientX;
                    //positioning and formatting, unimportant
                    var timeVal = (y-262)/500;
                    timeVal *= 900;
                    timeVal += 280;
                    var hour = Math.floor(timeVal/60);
                    var min = Math.round(timeVal%60,2);
                    var timeEnd = "AM";
                    if(hour>=12)
                        timeEnd = "PM";
                    if(hour>12)
                        hour-=12;
                    if(min<10)
                        min = "0"+min;
                    var timeCalc = hour+":"+min+" "+timeEnd;
                    document.getElementById("cbar").innerHTML = timeCalc;
                    document.getElementById("cbar").style.top = y - 262;
                    document.getElementById("cbar").style.textIndent = x - 950;
             });

Any suggestions are welcome, with or without jQuery.

You can try css pointer-events: none to make the unwanted div transparent to the mouse. This is probably the simplest and most efficient way if you imagine never needing any mouse interaction with the div.

If you do plan on having mouse interaction with the child element, then obviously that won't work. Instead of using clientX and clientY , try pageX and pageY relative to .calendar-part 's offset, as shown in this example .

Turns out that all I needed to do was add to the selector for this jQuery function, making it $(".calendar-part, .event") instead of just calendar-part . Works flawlessly. Anyone who forgets to think about this like I did, hopefully this helps!

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