首页 > 解决方案 > 如何使用 CSS 以像素为单位缩放元素?

问题描述

元素可以用 缩放transform: scale(sx),其中sx是(无单位)比例因子。有没有办法将元素缩小一定数量的像素(不知道它的宽度)。

编辑

我想在按下按钮时调整不同大小的元素的大小,例如按钮。但是,在所有按钮上应用相同的比例因子,例如scale(.95),会导致较大(较小)的按钮被缩放太多(小)。所以,我想做的是在绝对按下时调整所有元素的大小,即按一定数量的像素或 em 左右。

标签: css

解决方案


这就是您可以使用 vanilla JavaScript 缩放宽度的方法

const reduction=10;//in pixels
let button = document.querySelector("#myButton");
button.addEventListener("click",(event)=>{
  let style=window.getComputedStyle(button);
  let realWidth=parseInt(style.width);
  console.log(realWidth);
  let newWidth=realWidth-reduction;//some redundancy here
  button.style.width=`${newWidth}px`;//this changes the actual width property. With jQuery it would be even easier.
},false);
#myButton{
width:300px;
height:50px;
}
<button id="myButton">Click here to resize</button>


推荐阅读