CSS:在背景图像上更改光标

par*_*sis 8 css cursor background-image

我有一个背景图像作为CSS中的body类的一部分:

body.soon1 {
    background-color: white;
    background-image: url(soon1a.png);
    background-position: center;
    background-repeat: no-repeat;
}
Run Code Online (Sandbox Code Playgroud)

然后我有一个javascript函数,将改变体类.

我在后台运行图像的原因是,当脚本激活时,背景颜色和背景图像将在完全相同的时间发生变化,您无法选择图像.

是否有可能只在将鼠标悬停在背景图像上时更改光标类型?我明白我可以

cursor: pointer;
Run Code Online (Sandbox Code Playgroud)

在体型中,但这使光标出现在整个页面上.

您可以查看当前实时页面,当您单击页面上的任何位置时背景发生变化.

编辑:我现在有一些对我有用的东西.我添加了一个没有任何内容的居中div:

div.clickme {
width:300px;
height:400px;
position:absolute;
left:50%;
top:50%;
margin:-150px 0 0 -200px;
cursor: pointer;
}
Run Code Online (Sandbox Code Playgroud)

这对我有用,因为我可以设置我自己的任意区域,但如果有人有更好的解决方案,请告诉我.

Toh*_*huw 5

确实没有令人信服的理由将图像设为背景图像。将图像放在两个包装器中会更好地服务(无论视口如何,都需要保证垂直和水平绝对居中)。

您可以通过用对象填充数组来扩展数组,以便它可以保存图像和正文样式的可能值。这样,您可以使用相同的方法(循环遍历数组)挑选出您想要的所有更改,即使您想稍后添加其他更改。

此外,虽然 Web 浏览器对标准相当宽松,但要符合简单的 HTML 5 要求并仍然保留功能确实是微不足道的。

最后,我强烈建议您避免使用我所说的“时髦编码”。虽然用晦涩的名称来命名函数、变量很有趣,以取悦少数检查源代码的人,但它会导致语言变得不必要的钝化和较低的可维护性。简而言之,这是一种不好的做法,即使您是唯一的维护者。

根据下面的这些注释(带有缩进清理)观察您的源代码的新版本。

<html>
<head>
    <title>Something Amazing Will Happen</title>
    <style type="text/css">
        body.light {
            background-color: white;
        }
        body.dark {
            background-color: black;
        }
        div.outside-wrapper {
            position: absolute;
            top: 50%;
            width: 100%;
            height: 1px;
            overflow: visible;
        }
        div.inside-wrapper {
            position: absolute;
            top: 50%;
            left: 50%;
            width: 381px;
            height: 393px;
            margin: -197px 0 0 -191px;
            cursor: pointer;
        }
     </style>
     <script type="text/javascript">
         styleIndex = 0;
         var states = [{style: "light", image: "soon1a.png"}, {style: "dark", image: "soon2a.png"}];
         function nextStyle() {
             if (++styleIndex >= states.length)
                 styleIndex = 0;
             var state = states[styleIndex]; 
             document.body.className = state.style;
             document.getElementById("clickme").src = state.image;
         }
         var tap = true;
         document.addEventListener('touchstart',function(e) {
             tap = true;
         });
         document.addEventListener('click',function(e) {
             nextStyle()
             tap = false;
         });
         document.addEventListener('touchmove',function(e) {
             tap = false;
         });
         document.addEventListener('touchend',function(e) {
             if(tap)
                 nextStyle();
         });
    </script>
</head>
<body class="light">
    <div class="outside-wrapper">
        <div class="inside-wrapper">
        <img src="soon1a.png" id="clickme">
        </div>
    </div>
</body>
</html>
<!-- Don't ask me what it is. -->
Run Code Online (Sandbox Code Playgroud)