iT邦幫忙

0

javascript 取得滑鼠位置在IE會有錯誤訊息

以下是取得滑鼠位置的javascript語法,再chrome跟firefox不會錯,但是在IE 8會有錯誤

// Temporary variables to hold mouse x-y pos.s
var mouseX = 0
var mouseY = 0
// Detect if the browser is IE or not.
// If it is not IE, we assume that the browser is NS.
var IE = document.all?true:false

// If NS -- that is, !IE -- then set up for mouse capture
if (!IE) document.captureEvents(Event.MOUSEMOVE)

// Set-up to use getMouseXY function onMouseMove
document.onmousemove = getMouseXY;

// Main function to retrieve mouse x-y pos.s

function getMouseXY(e) {
if (IE) { // grab the x-y pos.s if browser is IE
mouseX = event.clientX + document.body.scrollLeft
mouseY = event.clientY + document.body.scrollTop
} else { // grab the x-y pos.s if browser is NS
mouseX = e.pageX
mouseY = e.pageY
}
return true
}

會出現這兩排錯誤,指出此處需要物件
mouseX = event.clientX + document.body.scrollLeft
mouseY = event.clientY + document.body.scrollTop

望各位前輩幫忙,謝謝

1 個回答

2
外獅佬
iT邦大師 1 級 ‧ 2014-10-06 11:58:12
最佳解答

lungzen提到:
mouseX = event.clientX + document.body.scrollLeft
mouseY = event.clientY + document.body.scrollTop

改成這樣試試

<pre class="c" name="code">
mouseX = event.clientX + document.documentElement.scrollLeft;
mouseY = event.clientY + document.documentElement.scrollTop;

我要發表回答

立即登入回答