function scrollfun()
{
var ob = document.getElementById('rowScroll');
ob.style.height ="300px";
ob.style.width = "200px";
}
此处rowScroll
是<div>
ID。上面的代码工作正常。但是以下代码不起作用:
function scrollfun()
{
var ob = document.getElementById('rowScroll');
ob.style.height ="30%";
ob.style.width = "20%";
}
如何才能使用百分比?
答案 0 :(得分:0)
您需要使用div标签来实现此目的。请参阅以下工作代码:
<!DOCTYPE html>
<html>
<head>
<script>
function displayResult()
{
document.getElementById("b1").style.height="200%";
}
</script>
</head>
<body>
<div style="height:25px;">
<input type="button" id="b1" onclick="displayResult()" value="Change height of button" >
</body>
</html>
答案 1 :(得分:0)
如果你“告诉”这些百分比是什么怎么办?像
function scrollfun()
{
var ob = document.getElementById('rowScroll');
ob.style.height = (container-width * 30)/100 + "px"
ob.style.width = (container-width * 20)/100 + "px"
}
答案 2 :(得分:0)
基于FYI百分比的宽度高度取决于元素'rowScroll'的父容器。尝试给父母本身提供身高,宽度信息......
更新:
使高度宽度为屏幕跟随的50%将执行:
function windowHW() {
var myWidth = 0, myHeight = 0;
if( typeof( window.innerWidth ) == 'number' ) {
//Non-IE
myWidth = window.innerWidth;
myHeight = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
//IE 4 compatible
myWidth = document.body.clientWidth;
myHeight = document.body.clientHeight;
}
return [myHeight,myWidth];
}
function scrollfun()
{
var ob = document.getElementById('rowScroll');
document_dimension = windowHW();
ob.style.height =document_dimension[0]/2;
ob.style.width =document_dimension[1]/2;
}
请注意,函数windowHW是对以下内容中给出的解决方案的略微修改:
stackoverflow question: JavaScript - Get Browser Height 回答了{p> meder答案 3 :(得分:0)
只需使用javascript
中的属性className
即可
function scrollfun()
{
document.getElementById("rowScroll").className = "MyClass";
}
在你的CSS中
.MyClass{height:30%;width:20%;}