如何将按钮高度设置为视口高度

时间:2017-09-22 22:07:56

标签: javascript jquery html css

我这样做是为了获得视口高度并设置按钮高度

var viewportHeight = $(window).height();
var viewPortHeightStr = `\"${viewportHeight}px\"`
document.getElementById("button").style.height = viewPortHeightStr
console.log('viewPortHeightStr = '+viewPortHeightStr) // prints "750px"

控制台日志"750px"但按钮的高度不受影响,但这可以正常工作

document.getElementById("button").style.height = "750px"

为什么?

这是按钮标签

<button id="button" class="btn-basic">x</button>

2 个答案:

答案 0 :(得分:1)

CSS很容易。使用:

height: 100vh;

这意味着100%的视口高度。

在您的代码中,问题似乎是:

var viewPortHeightStr = `\"${viewportHeight}px\"`
// change it to:
var viewPortHeightStr = viewportHeight + 'px';

段:

var viewportHeight = $(window).height();
var viewPortHeightStr = viewportHeight + 'px';
document.getElementById("button").style.height = viewPortHeightStr
console.log('viewPortHeightStr = '+viewPortHeightStr) // prints "750px"
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button" class="btn-basic">x</button>

答案 1 :(得分:0)

应该是

document.getElementById("button").style.height(viewPortHeightStr);

而不是

document.getElementById("button").style.height = viewPortHeightStr