Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.9k views
in Technique[技术] by (71.8m points)

css 点击ul切换其中li标签内的图片

如下图所示,在ul内有两个li标签,一个放图片一个显示文字。现在我希望当鼠标移动到图片上时,图片切换,并且字体颜色改变,点击后任然是这右边的样式。

总之,就是点击后切换样式,当点击其他位置时变成原来的样式。

目前使用了hover和active,只在hover的变化,点击之后鼠标移开样式就没有了,因为active只在鼠标按下时才有用。

我的问题是,如何保持鼠标按下后样式改变,只有在点击其他位置的时候才变回原来的样式呢?必须要给ul写一个onClick事件来改变样式吗?

image.png

ul代码

    <ul>
        <li><img src={count}/></li>
        <li>数量</li>
    </ul>

less代码

.iconContainer ul:nth-child(1):hover{
    li:nth-child(1){
        background-image: url("./Images/count.png");
        box-shadow: 5px 9px 15px 0px 
        rgba(10, 37, 90, 0.7);
        border-radius: 10px;
    }
    
    li:nth-child(2){
    font-size: 34px;
    color:#ffffff;
    text-align: center;
    margin-top: 20px;
}
}

.iconContainer ul:nth-child(1):active{
    li:nth-child(1){
        background-image: url("./Images/click-count.png");
        box-shadow: 5px 9px 15px 0px 
        rgba(10, 37, 90, 0.7);
        border-radius: 10px;
    }

    li:nth-child(2){
        font-size: 34px;
        color:#ffffff;
        text-align: center;
        margin-top: 20px;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

方案一
再li标签下面增加一个button,长宽为图片长宽,背景设置到button当中监听button:focus
方案二
再li标签下面增加一个button,长宽为图片长宽,设置button背景为transparent(透明背景),监听li标签的:focus-within
方案三
把li标签放在button当中,监听button:focus

其中除了方案二,需要设置背景为transparent外,其他的需要设置以下样式清除指定button默认样式

// 此处为全局设置,根据实际情况设置class啥的
    button{
        border: none;
        background: none;
        padding: none;
    }
    button:focus{
        outline: none;
    }   

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.5k users

...