简体   繁体   English

如何在 JavaScript 中将 CSS 属性作为 function 实现?

[英]How to implement zoom CSS property as a function in JavaScript?

I want to implement a function for the zoom css property in JavaScript;我想为 JavaScript 中的zoom css 属性实现 function; like how it is implemented in Chrome on Mac OS or Windows.就像它在 Mac OS 上的 Chrome 或 Windows 中的实现方式一样。 This is because this is a non-standard property and its implementation can vary across browsers (Mozilla Firefox does not support it).这是因为这是一个非标准属性,其实现可能因浏览器而异(Mozilla Firefox 不支持它)。 I do not want to use the transform: scale() property because it does not change the actual size of the element within the DOM (unlike like zoom ).我不想使用transform: scale()属性,因为它不会改变 DOM 中元素的实际大小(与zoom不同)。

I am not sure how I would go on about doing this.我不确定我将如何 go 这样做。 For my case, I have an input with placeholder text and background image which I want to zoom to 1.1.就我而言,我有一个包含占位符文本和背景图像的输入,我想将其缩放到 1.1。

The code below is just a way to show the difference in zoom and scale for my case:下面的代码只是显示我的案例的缩放和比例差异的一种方式:

 const searchbar = document.getElementById("searchbar-1") const zoom = (element, value) => { } zoom(searchbar, 1.1)
 .searchbar { background-image: url("https://static.thenounproject.com/png/3134345-200.png"); background-repeat: no-repeat; background-size: 1.2vw auto; background-position: 1.7vw center; font-size: 1.2vw; box-sizing: border-box; padding: 1.5vw 0vw 1.5vw 4vw; border: none; border-radius: 4px; box-shadow: 0vw 0.29282576866764276vw 1.4641288433382138vw rgba(32, 32, 32, 0.16); width: 150px; height: auto; } #searchbar-1:hover { zoom: 1.1; /* Wrapping div border changes with zoom */ } #searchbar-2:hover { transform: scale(1.1); /* Wrapping div border does not change with scale */ } div { border: 1px solid red; margin: 0px 0px 50px 0px; }
 <div><input placeholder="City" class="searchbar" id="searchbar-1" /></div> <div><input placeholder="City" class="searchbar" id="searchbar-2" /></div>

You can just use style.setProperty(string, string) .您可以只使用style.setProperty(string, string) The first parameter is the CSS atttribute and the second parameter is the CSS value .第一个参数是CSS 属性,第二个参数是CSS 值 Both of them need to be strings in order to work.它们都需要是strings才能工作。

const searchbar = document.getElementById("searchbar-1")

const zoom = (element, value) => {
  element.style.setProperty('zoom', value);
}

zoom(searchbar, '1.1')

I hope it helps you!我希望它对你有帮助! Happy coding!快乐编码!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM