【问题标题】:why does my custom-made "cursor" falls behind the moving div elements when i hover over them?当我将鼠标悬停在移动的 div 元素上时,为什么我的定制“光标”落在它们后面?
【发布时间】:2022-11-15 10:16:08
【问题描述】:

大家好希望你们今天过得愉快! 所以,我正在构建一个简单的游戏,其中我使用定制的光标作为射击 div 元素作为敌人在屏幕上移动的目标,当我应用“pointerdown”事件时,我希望敌人改变它的颜色。但是,每次我将鼠标悬停在敌人上方时,光标都会落后于女巫,我不明白为什么,当我使用 z-index 属性时,它会阻止“pointerdown”事件触发。如果一些很酷的 OG 程序员可以帮助我,那对我来说意义重大。

风格

* {
margin: 0;
padding: 0;
cursor: none;
}

.aim {
position: absolute;
background: black;
width: 10px;
height: 10px;
border-radius: 50%;
transform: translate(-50%, -50%);
}

.enemy {
position: absolute;
border: 3px solid black;
background-color: blue;
width: 50px;
height: 50px;
}

javascript

const body = document.body;
const aim = document.createElement("div");
const enemy = document.createElement("div");

body.appendChild(aim);
body.appendChild(enemy);

aim.classList.add("aim");
enemy.classList.add("enemy");

let enemy_X_position = 0;
let enemy_Y_position = 0;
let enemy_X_distance = 1;
let enemy_Y_distance = 1;

function Flight()
{
    enemy.style.left = enemy_X_position + "px";
    enemy.style.top = enemy_Y_position + "px";
}

setInterval(function()
{
    enemy_X_position += enemy_X_distance;
    enemy_Y_position += enemy_Y_distance;

    if ((enemy_X_position + enemy.offsetWidth) >= window.innerWidth || enemy_X_position <= 0)
    enemy_X_distance = -enemy_X_distance;

    if ((enemy_Y_position + enemy.offsetHeight) >= window.innerHeight || enemy_Y_position <= 0)
    enemy_Y_distance = -enemy_Y_distance;

    Flight();
},1000/60)

window.onmousemove = function()
{
    aim.style.left = event.pageX + "px";
    aim.style.top = event.pageY + "px";
}

enemy.onpointerdown = function()
{
    event.target.style.background = "red";
}

enemy.onpointerup = function()
{
    event.target.style.background = null;
}

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    也许是一个过度简化的解决方案,但似乎如果你颠倒appendChild 的顺序,aim 应该堆叠在enemy 之上,而不需要额外的样式。

    例子:

    body.appendChild(enemy);
    body.appendChild(aim);
    

    因为这两个元素都是body 的子元素,除非有其他样式覆盖此堆叠,否则后一个应该在最上面。

    【讨论】:

    • 我试过了,但仍然阻止事件触发
    猜你喜欢
    • 2014-01-31
    • 2014-11-18
    • 1970-01-01
    • 1970-01-01
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 2014-05-31
    相关资源
    最近更新 更多