Mouse movement problem on a webpage ( JavaScript )
I have 2 set of code
The following works on firefoxx=e.clientX + document.documentElement.scrollLeft;
y=e.clientY +document.documentElement.scrollTop -67;
and this works on Chrome
x=e.clientX + document.bo开发者_JAVA技巧dy.scrollLeft ;
y=e.clientY + document.body.scrollTop - 67 ;
i tried to combine the code , but it doesn't work properly in Firefox then.
if( document.documentElement){
x=e.clientX + document.documentElement.scrollLeft;
y=e.clientY +document.documentElement.scrollTop -67;
}
if( document.body){
x=e.clientX + document.body.scrollLeft ;
y=e.clientY + document.body.scrollTop - 67 ;
}
Why is this happening ?
My html is some thing like this , Does this have some thing to do with it?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
Position stuff is a royal pain. It looks like you have to use both of them. There's very similar code in the jQuery source which may help:
if ( event.pageX == null && event.clientX != null ) {
var doc = document.documentElement,
body = document.body;
event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
}
I don't know why they're doing that (on first glance, that code looks unnecessarily complicated) but I'm guessing there's a good reason, so you might try doing the same thing. That, adapted to your situation, might look like this:
var doc = document.documentElement,
body = document.body;
x = e.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
y = e.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0) - 67;
Somewhat off-topic: For positioning stuff, I'd really use a library like jQuery, YUI, Closure, Prototype, or any of several others. Then you get the benefit of lots of eyes on the code, lots of people using the code and reporting edge cases, etc., etc.
It's due to an old WebKit issue (which is closed as WontFix for some reason).
You can do something like what T.J. Crowder said, but it's somewhat costy. Your best bet is
feature testing scroll values (but only after the document is ready!).
var SCROLL_ROOT = (function() {
var html = document.documentElement,
scrollTop = html.scrollTop,
root;
html.scrollTop++;
root = (html.scrollTop != scrollTop + 1) ? document.body : html;
html.scrollTop--;
return root;
})();
And your code becomes
x = e.clientX + SCROLL_ROOT.scrollLeft;
y = e.clientY + SCROLL_ROOT.scrollTop - 67;
精彩评论