html - 更改使用 css + png 构建的按钮的状态

标签 html css png state

我正在尝试以最有效的方式为我的按钮构建样式。我有一门课叫 .button-small包含按钮的所有颜色和暗淡:

.button-small {
background: linear-gradient(to bottom,  #59aeee 1%,#4ea0dc 100%); /* W3C */
border-radius: 3px;
cursor: pointer;
width: 20px;
height: 20px;
}

我想向该类添加所有必需的状态,.button-small:active

既然这是一个简单的部分,接下来就是斗争。我有几个按钮,它们都有不同的 png文件,所以我决定创建单独的类,只包含有关图像 url 的附加信息,即:

.user-chat {
background: url('images/userchat.png') center center no-repeat;
}

上述问题曾经应用于 HTML 代码,<div class="button-small user-chat"></div> , background:属性正在从主 .button-small 中剥离有关颜色的信息类(class)。我知道我可以将有关背景的信息添加到代码中,这是我之前所做的:

.user-chat {
background: url('images/userchat.png') center center no-repeat, linear-gradient(to bottom,  #73b5e7 1%,#429be0 100%)`
}

但是为了向代码中添加不同的按钮状态,我必须为每个按钮复制代码,因为我有大约 30 个按钮,所以效率不是很高。

所以我真正想要的是一行代码,它允许我插入不同的透明背景 png按钮顶部的图像,无论按钮的状态如何。是否有这样的事情,如果没有,完成工作的最有效方法是什么?

最佳答案

您不妨考虑使用伪元素。当我像您一样需要多个背景图片时,我通常会这样做。

你可以做类似的事情:

.button-small {
    position: relative; /* So we can position our ::before element as needed */
}

/* Generic styles for pseudo elements */
.button-small::before {
    content: ''; /* required for pseudo elements to work */
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
}

/* You would now add your additional classes */
.user-chat::before {
    background: url(../something/goes/here.png) center center no-repeat;
}

这段代码应该在 IE9 以上版本中工作。如果您支持 IE8,请使用 :before 而不是 ::before

对于悬停和事件状态,您可以:

.user-chat:hover::before,
.user-chat:active::before,
.user-chat:focus::before {
    background-image: url(new/image.png); 
    /* Only need to override the image URL if position stays the same */
}

关于html - 更改使用 css + png 构建的按钮的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25608841/

相关文章:

html - Angular2 @ViewChild ElementRef offsetHeight 始终为 0

html - Bootstrap 字体文件夹

CSS:如何在动态宽度容器内强制宽度?

Delphi,处理 png 和位图的 ImageList

python - 如何在使用 BeautifulSoup 忽略格式化标签的同时从 html 中获取文本?

php - 双 if 与数据库查询

html - 对齐响应式 div

"border-radius"值的 Javascript/jQuery 正则表达式

java - 没有阅读器与 Java.ImageIO 中的 PNG-Stream 匹配

java - PNGj,元数据不被保存