在javascript中使box边缘跟随鼠标指针
making box edge follow mouse pointer in javascript
我不明白为什么这不起作用。我这里有一个DIV制作的黑色画布。在这个画布上,我希望用户定义我成功的第一个点,但在单击第一个点后,当鼠标移动时,框的大小必须正确,并跟随鼠标,就像在绘图程序中绘制矩形框一样。这是我遇到困难的地方。
有没有一种方法可以解决这个问题,使其在不使用Jquery的情况下最低限度地工作?如果我能为InternetExplorer7(或至少8)找到一个解决方案,那就更好了。
<div ID="CANVAS" style="background:#000;width:600px;height:400px"></div>
<script>
var startx=-1,starty=-1,points=0,box;
var canvas=document.getElementById('CANVAS');
canvas.onclick=dopoint;
canvas.onmousemove=sizebox;
function dopoint(e){
if (points==0){
var area=canvas.getBoundingClientRect();
box=document.createElement('DIV');
box.style.position='relative';
box.style.border='2px solid yellow';
canvas.appendChild(box);
startx=e.clientX-area.left;
starty=e.clientY-area.top;
box.style.left=startx+'px';
box.style.top=starty+'px';
box.style.width='10px';
box.style.height='10px';
}
points=1-points;
}
function sizebox(e){
if (points==1){
var x=e.clientY,y=e.clientY; //here I'm thinking subtract old point from new point to get distance (for width and height)
if (x>startx){
box.style.left=startx+'px';
box.style.width=(x-startx)+'px';
}else{
box.style.left=x+'px';
box.style.width=(startx-x)+'px';
}
if (y>starty){
box.style.top=starty+'px';
box.style.height=(y-starty)+'px';
}else{
box.style.top=y+'px';
box.style.height=(starty-y)+'px';
}
}
}
</script>
您的代码几乎很好,除了一些小事情。我已经更正了它,并在我更改的行上写了一些评论。
https://jsfiddle.net/1brz1gpL/3/
var startx=-1,starty=-1,points=0,box;
var canvas=document.getElementById('CANVAS');
canvas.onclick=dopoint;
canvas.onmousemove=sizebox;
function dopoint(e){
if (points==0){
var area=canvas.getBoundingClientRect();
box=document.createElement('DIV');
box.style.position='absolute'; // here was relative and changed to absolute
box.style.border='2px solid yellow';
canvas.appendChild(box);
startx=e.clientX; // removed -area.left
starty=e.clientY; // removed -area.right
box.style.left=startx+'px';
box.style.top=starty+'px';
box.style.width='0px'; // updated to 0px instead of 10 so it won't "jump" after you move the mouse with less then 10px
box.style.height='0px'; // same
}
points=1-points;
}
function sizebox(e){
if (points==1){
var x=e.clientX,y=e.clientY; // here was x = e.clientY and changed to x = clientX
if (x>=startx){
box.style.left=startx+'px';
box.style.width=(x-startx)+'px'; // here it was x+startx and changed to x-startx
}else{
box.style.left=x+'px';
box.style.width=(startx-x)+'px';
}
if (y>starty){
box.style.top=starty+'px';
box.style.height=(y-starty)+'px';
}else{
box.style.top=y+'px';
box.style.height=(starty-y)+'px';
}
}
}
相关文章:
- 网站跟随鼠标滚动
- javascript中的鼠标指针实时
- 鼠标指针和鼠标左键闪烁
- Jquery:当鼠标指针进入和离开元素时,创建一个弹出窗口
- 单击时更改鼠标指针,释放时返回
- 当用户将鼠标指针放在窗体按钮上时,该按钮必须更改颜色
- 为什么不起作用?用鼠标指针推框
- 如何修复鼠标指针的问题
- 在鼠标指针下获取单词
- 三.js - 对象跟随鼠标位置
- 如何使用javascript加载页面时将鼠标指针移动到页面顶部
- Sikuli可以观察到鼠标指针的变化吗?(响应式鼠标与无响应鼠标)
- HTML 中跟随鼠标的动画图像蒙版
- 当鼠标指针放在图形区域内时,实时图形将停止
- 画布鼠标指针未同步
- HTML5 画布跟随鼠标效果 jquery
- D3:跟随鼠标坐标
- 在javascript中使box边缘跟随鼠标指针
- 图像跟随鼠标指针和淡出
- 如何让jQuery鼠标悬停工具提示跟随鼠标指针?