这是我的代码,用于减小选定元素的宽度(class =“ life_bar”),但是如我所附的图片所示,我希望它从左或向右减小宽度(以左为例),但它总是双方该怎么办?
这是jQuery代码
$(function () {
var timmer;
gocount();
function gocount(){
timmer = setInterval(function () {
var life_bar_width = $(".life_bar").width();
life_bar_width -= 100;
$(".life_bar").css( {width: life_bar_width,
left: '-50px'})
},1000);
}
});
这是CSS代码
.life_bar{
width: 500px;
height: 10px;
background: crimson;
margin: 100px auto;
}
这是HTML代码
<body>
<div class="life_bar"></div>
</body>
最佳答案
在每个间隔刻度上对X使用负平移:
$(function () {
var timmer;
gocount();
let counter = 1
function gocount(){
timmer = setInterval(function () {
var life_bar_width = $(".life_bar").width();
life_bar_width -= 100;
$(".life_bar").css({
width: life_bar_width,
left: '-50px',
transform: `translate(${-50*counter}px)`
})
counter++
},1000);
}
});
.life_bar{
width: 500px;
height: 10px;
background: crimson;
margin: 100px auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="life_bar"></div>