我遇到了以下问题:
单击时,我试图为绝对定位的 div 的位置、宽度和高度设置动画。此外,我正在尝试通过 jQuery 更改 background-size
。
发生的事情是它正确地更改了所有 CSS 属性,但不是 background-size
。
它应该将 background-size:100% auto
更改为 background-size:auto 100%
。它似乎忽略了这一点。
有谁知道为什么会出现这个问题?
$(".item").click(function(){
$(this).animate({
'width': '94vw',
'height': '94vh',
'top': '3vh',
'left': '3vw',
'background-size': 'auto 100%'
}, 500);
$(".again").fadeIn();
});
$('.again').click(function() {
location.reload();
});
*{
margin:0;
padding:0;
}
.item{
background:#a0a0a0;
width:50%;
height:100px;
position: absolute;
top:0;
left:0;
cursor:pointer;
overflow:hidden;
background-image:url("http://www.stefan-hefele.de/tl_files/Portfolio/Landschaft/Mallorca/Hochformate/9542_Mallorca%20Dawn.jpg");
background-size:100% auto;
background-position:center;
background-repeat:no-repeat;
}
.again{
display:none;
position:absolute;
bottom:20px;
width:100px;
left:calc(50% - 50px);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item"></div>
<button class="again">Again</button>
最佳答案
为什么不使用 CSS 转换结合类而不是 jQuery animate()
?
在这里,我使用类 .big
来切换您的 CSS 规则。我还在您的 .item
上添加了 transition: all .5s;
以启用转换。
$(".item").click(function() {
$(this).toggleClass('big');
});
* {
margin: 0;
padding: 0;
}
.item {
background: #a0a0a0;
width: 50%;
height: 100px;
position: absolute;
top: 0;
left: 0;
cursor: pointer;
overflow: hidden;
background-image: url("http://www.stefan-hefele.de/tl_files/Portfolio/Landschaft/Mallorca/Hochformate/9542_Mallorca%20Dawn.jpg");
background-size: 100% auto;
background-position: center;
background-repeat: no-repeat;
transition: all .5s;
}
.item.big {
width: 94vw;
height: 94vh;
top: 3vh;
left: 3vw;
background-size: auto 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item"></div>
关于javascript - jQuery 设置 `background-size` 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48683561/