Jquery - add css :active style inline



如何添加:active pceudo类,以便按钮可以在没有单独的全局CSS的情况下翻译点击?

const $button = $('<button></button>').css({
margin: '5px',
':active': 'transform: translate(0, 3px)',
})

根据您的要求,我的理解是,单击时要将 Y 按钮转换为 3px,一旦鼠标按钮离开,它应该恢复到正常位置,这意味着翻译 Y 0px。

所以:active的实际工作方式是,一旦你点击某些东西,它就会被激活,当你离开鼠标按钮时,它就会被停用。 像这样: 使用 CSS:

button {
color: red;
background: white;
border: 2px solid;
padding: 20px 40px;
display: block;
}
button:active {
transform: translate(0px,3px);
}
<button>Click</button>

现在用JQuery检查同样的事情。

$("button").mousedown(function(){
$(this).css('transform','translate(0,3px)')
});
$("button").mouseup(function(){
$(this).css('transform','translate(0,0px)')
});
button {
color: red;
background: white;
border: 2px solid;
padding: 20px 40px;
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Click</button>

如果我误解了您的要求,请告诉我,

或者,您可以在 head 中注入样式:

$('head').append('<style>.myClass:hover { background-color: red; }</style>')
$('<button>123</button>').addClass('myClass')

最新更新