Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/388.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在mousedown上创建新div_Javascript_Jquery_Html_Css - Fatal编程技术网

Javascript 在mousedown上创建新div

Javascript 在mousedown上创建新div,javascript,jquery,html,css,Javascript,Jquery,Html,Css,嗨,我想在mousedown上创建新的div,我想在鼠标移动时调整它的大小。但我似乎不能理解我犯的错误 var-x1; 变量y1; var=false; document.getElementById(“主”).onmousedown=function(){ 按下=真; var-ok=true; 如果(ok==真){ div=document.createElement('div'); div.style.backgroundColor=“黑色”; div.style.position=“绝对

嗨,我想在mousedown上创建新的div,我想在鼠标移动时调整它的大小。但我似乎不能理解我犯的错误

var-x1;
变量y1;
var=false;
document.getElementById(“主”).onmousedown=function(){
按下=真;
var-ok=true;
如果(ok==真){
div=document.createElement('div');
div.style.backgroundColor=“黑色”;
div.style.position=“绝对”;
x1=数学轮(event.clientX);
y1=数学轮(event.clientY);
div.style.left=x1+“px”;
div.style.top=y1+“px”;
div.setAttribute(“id”、“唯一标识符”);
document.getElementsByTagName('body')[0].appendChild(div);
}
};
document.getElementById(“主”).onmousemove=function(){
如果(按下){
var div=get.getElementById(“uniqueIdentifier”);
var x2=数学轮(event.clientX)+x1;
var y2=Math.round(event.clientY)+y1;
div.style.width=x2+“px”;
div.style.height=y2+“px”;
}
}
document.getElementById(“主”).onmouseup=function(){
按下=假;
}
#主要{
高度:200px;
宽度:200px;
背景颜色:黄色;
}

您输入了一个错误
get.getElementById
应该是
document.getElementById
。当我解决这个问题时,代码就起作用了

var-x1;
变量y1;
var=false;
document.getElementById(“主”).onmousedown=function(){
按下=真;
var-ok=true;
如果(ok==真){
div=document.createElement('div');
div.style.backgroundColor=“黑色”;
div.style.position=“绝对”;
x1=数学轮(event.clientX);
y1=数学轮(event.clientY);
div.style.left=x1+“px”;
div.style.top=y1+“px”;
div.setAttribute(“id”、“唯一标识符”);
document.getElementsByTagName('body')[0].appendChild(div);
}
};
document.getElementById(“主”).onmousemove=function(){
如果(按下){
var div=document.getElementById(“uniqueIdentifier”);
var x2=数学轮(event.clientX)+x1;
var y2=Math.round(event.clientY)+y1;
div.style.width=x2+“px”;
div.style.height=y2+“px”;
}
}
document.getElementById(“主”).onmouseup=function(){
按下=假;
}
#主要{
高度:200px;
宽度:200px;
背景颜色:黄色;
}

为什么分配后立即测试
ok
?它将始终是您刚才分配的值。
get.getElementById
应该是
document.getElementById
我是JS新手。是否可以针对任何元素而不仅仅是特定id或类?是的。如果您有一个包含该元素的变量,则可以向其中添加一个事件侦听器。例如,您可以同时执行
div.onclick=function()…
我的意思是,您可以将它放在
body
上,这样当您单击任何位置时,它都会触发。您可能还必须为正在使用鼠标移动的div禁用pointerevents。