【笔记JS/HTML/CSS】用div实现个性化button,背景半透明

html中的button默认样式..不太能看,如果调一调背景色和字体的话也挺适合简洁的页面设计

于是决定配合JS,用html中的div完成button

最终结果图:

html代码:(first_passer.png是“过路人”字样的背景透明图片)

<div class="button" id="button3"><img id="button3_img" src="images/first_passer.png"></div>

(命名可以任意)

css代码:

    margin-top: 20%;
    height: 12%;/*长宽应该要按照自己的代码设置,此处外层有嵌套,所以用百分比*/
     100%;
    border-radius: 10px;
    border: 1px solid black;
    text-align: center;
    background:rgba(255, 251, 240, 0.3); /*R G B opacity*/

JS实现的功能:鼠标覆盖时0.5透明度,离开时0.3透明度,并且读取浏览器宽高,自适应设置div长宽,设置div中图片高度与div相同,宽度auto。

$("button3_img").style.height = screen.availHeight * 0.70 * 0.7 * 0.12 + "px";

$("button3_img").style.width = "auto";

因为div的高度也是根据screen.availHeight的百分比来设置的,所以此处可用screen.availHeight * 0.70 * 0.7 * 0.12表示div高。

下面的JS代码时用来设置鼠标指向和离开button时,背景透明度的变化:

$("button3").onmouseover = passerby_move;

$("button3").onmouseout = passerby_out;

function passerby_out() {
    $("button3").style.background = "rgba(255, 251, 240, 0.3)";
}

function passerby_move() {
    $("button3").style.background = "rgba(255, 251, 240, 0.5)";
}

PS:差点忘了,此处的$是自己设置的,不是jQuery,代码如下:

$=function (id) {
    return document.getElementById(id);
}

原文地址:https://www.cnblogs.com/cheermyang/p/4814360.html