因此,我在页面中间有一个图像(我希望它保留在那里(,当我握住LMB时,我希望它变小一点,然后在发布时恢复到以前的大小。
代码下方:
$(document).ready(function() {
$("#banana").mousedown(function() {
$("#banana").css("height","70%");
});
$("#banana").mouseup(function() {
$("#banana").css("height","100%");
});
});
.centered {
text-align: center;
display: block;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div id = "banana" class = "centered">
<img src="https://via.placeholder.com/150" alt="banana.png">
</div>
</body>
我尝试使用jQuery获取该目标(但图像的位置发生了变化,不再居中(。
提前感谢!
只使用CSS,使用:active
伪选择器(对应于"mousedown"(,这很容易做到。另外,为什么不使用Flex轻松居中。
.container {
border: #00f solid 1px;
width: 250px;
height: 250px;
display: flex;
justify-content: center;
align-items: center;
}
.container img {
transition: all 0.3s ease-in-out;
transform: scale(1);
}
.container img:active {
transform: scale(0.8);
}
<div class="container"><img src="https://via.placeholder.com/150"/></div>
尝试
transform: scale(0.7)
而不是高度。它将以中心为中心,并且更高效(GPU使用(
将LMB放在图像上而不是div上,并使用宽度而不是高度
$(document).ready(function() {
$("#pic").mousedown(function() {
$("#pic").css("width","70%");
});
$("#pic").mouseup(function() {
$("#pic").css("width","100%");
});
});
.centered {
text-align: center;
display: block;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div id = "banana" class = "centered">
<img id='pic' src="https://picsum.photos/300" alt="banana.png">
</div>
</body>
在你的身体上添加和删除一个类,并间接转换你的图像:
$(document).ready(function() {
const body = $('body');
const cssClassClicked = 'lmb-clicked';
body
.mousedown(function() {
body.toggleClass(cssClassClicked)
})
.mouseup(function() {
body.toggleClass(cssClassClicked)
});
});
body {
min-height: 100vh;
background: #eee;
display: flex;
flex-flow: column nowrap;
justify-content: center;
align-items: center;
}
.img {
display: block;
transition: transform 300ms ease-in-out;
will-change: transform;
}
.lmb-clicked .img {
transform: scale(0.9);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class="img" src="https://picsum.photos/id/1/400/300">
这应该有效:
$(document).ready(function() {
$("#banana").mousedown(function() {
$("#banana").css("height","50vh");
});
$("#banana").mouseup(function() {
$("#banana").css("height","100vh");
});
});
.centered {
text-align: center;
display: block;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<body>
<div class = "centered">
<img id = "banana" src="https://www.chiquita.com/wp-content/uploads/2019/12/Chiquita_Banana_Class_Extra_Yellow.jpg" alt="banana.png">
</div>
</body>