您好我想创建新的div onmousedown,我想在鼠标移动时调整它的大小。但我似乎无法解决我所犯的错误。
var x1;
var y1;
var pressed = false;
document.getElementById("primary").onmousedown = function() {
pressed = true;
var ok = true;
if (ok === true) {
div = document.createElement('div');
div.style.backgroundColor = "black";
div.style.position = "absolute";
x1 = Math.round(event.clientX);
y1 = Math.round(event.clientY);
div.style.left = x1 + "px";
div.style.top = y1 + "px";
div.setAttribute("id", "uniqueIdentifier");
document.getElementsByTagName('body')[0].appendChild(div);
}
};
document.getElementById("primary").onmousemove = function() {
if (pressed) {
var div = get.getElementById("uniqueIdentifier");
var x2 = Math.round(event.clientX) + x1;
var y2 = Math.round(event.clientY) + y1;
div.style.width = x2 + "px";
div.style.height = y2 + "px";
}
}
document.getElementById("primary").onmouseup = function() {
pressed = false;
}

#primary {
height: 200px;
width: 200px;
background-color: yellow;
}

<div id="primary"></div>
&#13;
答案 0 :(得分:2)
你有一个错字。 get.getElementById
应为document.getElementById
。当我修复它时,代码可以工作。
var x1;
var y1;
var pressed = false;
document.getElementById("primary").onmousedown = function() {
pressed = true;
var ok = true;
if (ok === true) {
div = document.createElement('div');
div.style.backgroundColor = "black";
div.style.position = "absolute";
x1 = Math.round(event.clientX);
y1 = Math.round(event.clientY);
div.style.left = x1 + "px";
div.style.top = y1 + "px";
div.setAttribute("id", "uniqueIdentifier");
document.getElementsByTagName('body')[0].appendChild(div);
}
};
document.getElementById("primary").onmousemove = function() {
if (pressed) {
var div = document.getElementById("uniqueIdentifier");
var x2 = Math.round(event.clientX) + x1;
var y2 = Math.round(event.clientY) + y1;
div.style.width = x2 + "px";
div.style.height = y2 + "px";
}
}
document.getElementById("primary").onmouseup = function() {
pressed = false;
}
&#13;
#primary {
height: 200px;
width: 200px;
background-color: yellow;
}
&#13;
<div id="primary"></div>
&#13;