我正在尝试使用 JS/HTML/CSS 创建一个屏幕锁定图案网页。我在这里找到了一个已经为鼠标事件做了这个的人的源代码: text(点击查看源页面)。我试着调整他的代码以适应触摸事件,这里是我修改后的脚本:
var log=console.log;
function op(elem){return document.querySelector(elem)}
function opp(elem){return document.querySelectorAll(elem)}
var lockBox=op('.lockBox');
for(var a=0; a< 15; a++){
lockBox.insertAdjacentHTML("afterbegin",`<div class="dot"><div class="dotArea" ontouchstart="TouchStart(this)"><i>${a}</i></div></div>`)
}
var startDot,
svg=op("svg"),
dots=opp(".dot"),
lineData="M",
tempLineData,
svgPath=op('svg path'),
inputData="";
function end(){
document.body.style.setProperty('--baseCol',(inputData.length === 5)?"#0f0":"#f00");
startDot=undefined;
lineData="M";
inputData="";
tempLineData=undefined;
setTimeout(()=>{
opp('.dot.active').forEach(val=>{val.classList.remove('active')})
svgPath.setAttribute("d",'');
document.body.style.setProperty('--baseCol',"#00cbff");
},500)
}
function TouchStart(elem){
startDot=elem;
document.addEventListener('touchmove', moving);
addEvToMouseEnter();
lineData+=`${startDot.parentElement.offsetLeft +5},${startDot.parentElement.offsetTop +5}`;
makeLine();
startDot.classList.add("active")
}
document.ontouchend=function (){
document.removeEventListener('touchmove', moving);
removeEvToMouseEnter();
tempLineData=''
updateLine();
end(startDot,tempLineData,lineData)
}
function moving(e){
makeLineWhileMoving(e.touches[0].clientX,e.touches[0].clientY)
}
function makeLineWhileMoving(x,y){
var x=Math.floor(x - lockBox.getBoundingClientRect().left);
var y=Math.floor(y - lockBox.getBoundingClientRect().top);
tempLineData=" L"+x+','+y;
updateLine()
}
function makeLine(e=startDot){
e.target=startDot;
var dot=e.target.parentElement;
dot.classList.add('active');
var x=dot.getBoundingClientRect().left,
y=dot.getBoundingClientRect().top;
inputData+=dot.innerText;
makeLineWhileMoving(x,y)
lineData+=tempLineData;
}
function addEvToMouseEnter(){
opp(".dotArea").forEach(val=>{
val.addEventListener("touchstart",makeLine);
})
}
function removeEvToMouseEnter(){
opp(".dotArea").forEach(val=>{
val.removeEventListener("touchstart",makeLine);
})
}
function updateLine(){
svgPath.setAttribute("d",lineData+tempLineData);
}
问题是我的代码没有连接点,它只是从触摸开始时触摸的点到用户手指的实际位置画一条线,即使当用户触摸一个新点时,原始代码也可以完美地工作看。 那是我第一次接触 JS,我不是一个很好的程序员,所以我真的不知道这是怎么回事。
我假设问题来自最后 3 个函数,所以我尝试直观地修改它们(自昨天以来至少修改了 10 次)。我什至试图从 ChatGPT 获得帮助,但没有成功。