我想在鼠标位置绘制水平和垂直线折叠。我面临两个问题
代码:
var element = document.getElementById('box');
var drawLines = function(event) {
var x = event.pageX;
var y = event.pageY;
var straightLine = element.querySelector('.straightLine');
var hrLine = element.querySelector('.hrLine');
var slTrans = 'translate(' + x + 'px, 0px)';
var hrTrans = 'translate(0px, ' + y + 'px)';
if(!straightLine) {
straightLine = document.createElement('div');
straightLine.classList.add('straightLine');
straightLine.style.height = "100%";
straightLine.style.width = '2px';
element.appendChild(straightLine);
}
straightLine.style.transform = slTrans;
if(!hrLine) {
hrLine = document.createElement('div');
hrLine.style.height = "2px";
hrLine.classList.add('hrLine');
hrLine.style.width = '100%';
element.appendChild(hrLine);
}
hrLine.style.transform = hrTrans;
}
element.addEventListener('mousemove', function(event) {
drawLines(event);
});
element.addEventListener('mousedown', function(event) {
drawLines(event);
});
element.addEventListener('mouseup', function(event) {
drawLines(event);
});
element.addEventListener('mouseout', function(event) {
drawLines(event);
});
答案 0 :(得分:3)
水平线问题可以通过以下方式解决:
.straightLine, .hrLine {
position: absolute;
background-color: red;
}
查看更新的fiddle。
修改强>
您还可以使用以下内容来平滑动画(您必须根据自己的需要调整时间跨度:
.straightLine, .hrLine {
position: absolute;
background-color: red;
transition: transform .05s ease-in-out;
}
查看更新的fiddle和w3schools.com。