Div仍为零读数

时间:2017-12-01 17:43:35

标签: javascript debugging console

第二部分由于某种原因读取null。它在第一部分工作。

window.onload = function() {
var div = document.createElement("div");
div.innerHTML = '<img alt="pickle" src="images/pickle">';
div.style.visibility = "visible";
div.style.position = "absolute";
div.style.zIndex = "3";
div.className = "jack";
document.body.appendChild(div);

第二部分

document.onmousemove=function(e){
  var x, y;
  if (e) {x=e.clientX; y=e.clientY;} 
  else {x=event.clientX;y=event.clientY;}
  var jack = document.getElementById('jack');
  jack.style.top=y+'px';
  jack.style.left=x+50+'px';
}};

&#13;
&#13;
window.onload = function() {
var div = document.createElement("div");
div.innerHTML = '<img alt="pickle" src="images/pickle">';
div.style.visibility = "visible";
div.style.position = "absolute";
div.style.zIndex = "3";
div.className = "jack";
document.body.appendChild(div);

document.onmousemove=function(e){
  var x, y;
  if (e) {x=e.clientX; y=e.clientY;} 
  else {x=event.clientX;y=event.clientY;}
  var jack = document.getElementByClassName('jack');
  jack.style.top=y+'px';
  jack.style.left=x+50+'px';
  }};
&#13;
<html>
<head>
</head>
<body>
</body>
</html>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

您正在定位#jack,但该元素没有ID,只有一个类。将以下内容添加到您要创建元素的代码部分。

div.id = "jack";

var div = document.createElement("div");
div.innerHTML = '<img alt="pickle" src="images/pickle">';
div.style.visibility = "visible";
div.style.position = "absolute";
div.style.zIndex = "3";
div.id = "jack";
document.body.appendChild(div);

document.onmousemove=function(e){
  var x, y;
  if (e) {x=e.clientX; y=e.clientY;} 
  else {x=event.clientX;y=event.clientY;}
  var jack = document.getElementById('jack');
  jack.style.top=y+'px';
  jack.style.left=x+50+'px';
};

答案 1 :(得分:0)

同样的故事: getElement s ByClassName()返回HTMLCollection(HTMLElements数组),getElement s ByClassName(&#34; css-class&#34;)[0]是找到的第一个HTMLElement

唯一的例外是getElementById()方法。它返回单个HTMLElement(因为id属性是唯一的 - 一个文档不能包含两个具有相同id值的元素)