怎么用js写按钮点击下去时颜色变深,松开按钮时未点击前的状态?

用onmousedown和onmouseup同时绑定统一目标元素,但是只有第一个函数起作用
尝试用其他函数绑定,依旧只有第一个函数起作用
js代码如下:

//点击中间确定按钮

function confirmBtn(){
    var aCenter = document.getElementById("confirmBtn");
    aCenter.onmousedown = function () {
        aCenter.style.boxShadow = "inset 0 0 50px #333";
        console.log( aCenter );
    }
    aCenter.onmouseup = function(){
        // aCenter.style.boxShadow = "0 0 0 transparent";
        console.log( aCenter );
    }
}
confirmBtn();
阅读 6.1k
6 个回答

1.确定只有第一个函数有用?我这边在控制台显示你的两个函数都console出来了,把第二个函数的注释去掉也可以有类似css active的效果。

function confirmBtn(){
    var aCenter = document.getElementById("confirmBtn");
    aCenter.onmousedown = function () {
        aCenter.style.boxShadow = "inset 0 0 50px #333";
        console.log( aCenter );
    }
    aCenter.onmouseup = function(){
        aCenter.style.boxShadow = "0 0 0 transparent";
        console.log( aCenter );
    }
}
confirmBtn();

2.另外这个为什么要用js模拟呢?可以用css的:active伪类做。

移动端的事件也不是 mousedown 了呀, 是toushstart ;
请详见: https://developer.mozilla.org/zh-CN/docs/Web/API/TouchEvent


如果答案对大家有用, 请点个赞, 非常感谢

css就能解决

#confirmBtn:active {
        box-shadow:inset 0 0 50px #333;
}

请使用事件委托addEventListener添加事件

图片描述

你的代码没错啊,还是你想要的效果不是你的代码的样式?
链接描述

点一下运行js,然后就是鼠标按下有阴影,鼠标抬起去掉阴影

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <script src="./jquery-3.2.1.js"></script>
  <style>
.div1{
width: 200px;
height:200px;
background: red;
}
  </style>
</head>
<body>
<div class="div1"></div>
  <script type="text/javascript">
$(function() {
    $('.div1').mousedown(function(){
        $(this).css({
            "background":"black"
        })
    }).mouseup(function(){
        $(this).css({
            "background":"green"
        })
    })
})
  </script>
</body>
</html>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题