当前位置: 代码迷 >> Web前端 >> 获取页面的滚动位置与鼠标事件中的座标
  详细解决方案

获取页面的滚动位置与鼠标事件中的座标

热度:20   发布时间:2012-11-11 10:07:57.0
获取页面的滚动位置与鼠标事件中的坐标
/**
    获取当前滚动的位置。
*/
function getScrollingPosition()
{
	var position = [0, 0];
    //FF
	if (typeof window.pageYOffset != 'undefined')
	{
		position = [
			window.pageXOffset,
			window.pageYOffset
		];
	}
    //IE
	else if (typeof document.documentElement.scrollTop
		!= 'undefined' && document.documentElement.scrollTop > 0 ||
		document.documentElement.scrollLeft > 0)
	{
		position = [
			document.documentElement.scrollLeft,
			document.documentElement.scrollTop
		];
	}
	else if (typeof document.body.scrollTop != 'undefined')
	{
		position = [
			document.body.scrollLeft,
			document.body.scrollTop
		];
	}
	return position;
}

属性描述(0,0)点
screenX事件发生时鼠标指针相对于屏幕的水平坐标屏幕左上角
screenY 事件发生时鼠标指针相对于屏幕的垂直坐标屏幕左上角
clientX 事件发生时鼠标指针相对于浏览器页面(客户区)的水平坐标 浏览器客户区左上角
clientY 事件发生时鼠标指针相对于浏览器页面(客户区)的垂直坐标浏览器客户区左上角
offsetX 事件发生时鼠标指针在事件元素中的水平坐标 元素左上角
offsetY 事件发生时鼠标指针在事件元素中的垂直坐标 元素左上角
x 事件发生时鼠标指针相对于用CSS动态定位的最内层包容元素的水平坐标
y 事件发生时鼠标指针相对于用CSS动态定位的最内层包容元素的垂直坐标
pageX 鼠标相对于页面的x坐标页面左上角
pageY 鼠标相对于页面的Y坐标页面左上角

说明:
    * offsetX、offsetY、x、y 属性只能用于IE浏览器。
    * pageX、pageY 属性用于非IE浏览器。
/**
   获取鼠标位置
*/
function displayCursorPosition(event)
{
  if (typeof event == "undefined")
  {
    event = window.event;
  }

  var scrollingPosition = getScrollingPosition();
  var cursorPosition = [0, 0];

  if (typeof event.pageX != "undefined" && typeof event.x != "undefined")
  {
    cursorPosition[0] = event.pageX;
    cursorPosition[1] = event.pageY;
  }
  else
  {
    cursorPosition[0] = event.clientX + scrollingPosition[0];
    cursorPosition[1] = event.clientY + scrollingPosition[1];
  }

  document.title = cursorPosition.toString();
}
  相关解决方案