我正在创建一个程序,允许用户更改 div 的大多数 CSS 属性。不过,我需要将其居中,我通常使用下面的 CSS 代码来实现此目的。
div {
position: fixed;
background: black;
width: 100px;
height: 100px;
top: calc(50% - 50px);
right: calc(50% - 50px);
}
然而,我需要将宽度和高度设为自己的变量,然后对顶部和右侧的属性进行计算,将它们除以 2 并减去 50%。
var width = 100;
var height = 100;
var top = (height / 2);
var right = (width / 2);
$('div')
.css('position','fixed')
.css('background','black')
.css('width',width + 'px')
.css('height',height + 'px')
.css('top','calc(50% - ' + top + 'px)')
.css('right','calc(50% - ' + right + 'px)');
如何在使用变量作为 CSS 属性值的同时实现居中的 div?
如果你不需要支持蹩脚的 IE CSS 变量是一个选择。
CSS
- 在样式表中选择一个范围。选择器在 DOM 上的位置越高,它覆盖的范围就越多。在片段中我选择了尽可能最高的:
:root
(i.e. html
).
- 声明 CSS 变量:
:root --half: 50px
CSSVar 必须以 2 个破折号为前缀。在代码片段中我已经声明了--half
on :root
与价值50px
.
- Next, assign CSSVar to the appropriate properties:
top: calc(50% - var(--half));
right: calc(50% - var(--half));
JavaScript
- 详细信息在片段中评论。
SNIPPET
// Reference the input
var A = document.getElementById('input1');
// On input event on input#A call setHalf() function
A.addEventListener('input', setHalf, false);
/* setHalf() accesses the CSS by the CSSDeclaration
|| interface.
*/
function setHalf(e) {
// Reference the div
var X = document.getElementById('shape1');
/* Get div#shape1 computedStyle in order to
|| access it's ruleset declarations.
*/
var Y = window.getComputedStyle(X);
// Get the value of the CSSVar --half
var Z = Y.getPropertyValue('--half');
// Set --half value to the value of input#A
X.style.setProperty('--half', this.value + 'px');
}
:root {
--half: 50px;
}
#shape1 {
position: fixed;
background: black;
width: 100px;
height: 100px;
top: calc(50% - var(--half));
right: calc(50% - var(--half));
border: 1px solid black;
}
<div id='shape1'></div>
<input id='input1' type='number' min='-150' max='150' value='50'>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)