如何使用JavaScript变量设置函数集css宽度

How to make a function set css width with a JavaScript variable?

本文关键字:css 宽度 函数 设置 何使用 JavaScript 变量      更新时间:2023-11-01

我有这个代码:

...<script>
function handleSize()
{
var setObjectSize=window.innerWidth - 600;
document.getElementById("spin").style.width=setObjectSize + "px";
document.getElementById("spin").style.height=setObjectSize + "px";
}
</script>
</head>
<body>
<section id="spin" onLoad="handleSize()">...

我所要做的就是创建一个函数,该函数将使用公式根据窗口大小设置元素的高度和宽度,并确保高度和宽度相同。我对javascript非常陌生(几乎一无所知),所以尽管有很多这样的问题的例子,而且我也在关注它们,但我无法让这些代码发挥作用。我做错了什么?

我看到的问题是section标记的onload事件没有启动。您应该将javascript作为一个自执行的匿名函数添加到body标记的末尾,这将对您有效。

    <body>
        <section id="spin" style="border:5px solid black;"></section>
        <script>
            (function () {
                var setWindowSize = window.innerWidth - 600;
                document.getElementById("spin").style.width = setWindowSize + "px";
                document.getElementById("spin").style.height = setWindowSize + "px";
            })();
        </script>
    </body>

有关演示,请参见此处:http://jsfiddle.net/T7DW6/

您应该将onload移动到body标签:

<body onLoad="handleSize()">
<section id="spin">...

我建议您使用jQuery,这是世界范围内使用的JavaScript库。因此,为了使用jQuery开发它,您需要进行下一次

function setElementSize(elId) {
   var _w $(window); //to get instance of window
   var _el $('#' + elId); //jquery to get instance of element
   var _width = _w.width();
   var _height = _w.height();
   //set width=height
   if(_height>_width)
   {
      _height = _width;     
   } else { _width = _height; }
   _el.css({
      width: _width,
      height: _height 
   });
}

//this will execute script when document is loaded.
     $(document).ready(function(){
       setElementSize('spin');
    });

上面的函数将设置元素的宽度和高度以匹配窗口大小。如果height>width,那么它将使用width作为width&高度,否则将使用高度。

我假设你想自动改变这个,如果窗口被调整大小,然后做这个

 $(window).resize(function(){
          setElementSize('spin');
    });

加载对象时会发生onload事件。

onload最常用于元素中,用于在网页完全加载所有内容(包括图像、脚本文件、CSS文件等)后执行脚本

onload仅受以下HTML标记的支持:body,frame,frameset,iframe,img,input type="image",链接,脚本,样式

从这里:event_onload

那么这里的is可能不是最好的(身高和体重不会改变任何东西,应该使用div。为了知道,要使用的,请阅读以下内容:section和div 有什么区别

我试了试你的考试,结果很好。我唯一改变的是你调用函数的方式

   function handleSize(){
            var setWindowSize=window.innerWidth - 600;
            document.getElementById("spin").style.width=setWindowSize + "px";
            document.getElementById("spin").style.height=setWindowSize + "px";
            }
            window.onload = function () {
                handleSize();
 }

我认为onLoad="handleSize()"必须是onload="handleSize()",但不要这样使用,因为这不是一个好的练习!

这对我有效

<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button and watch it grow.</p>
<button id = "myButton" onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var w = window.innerWidth;
var h = window.innerHeight;
var x = document.getElementById("myButton");
x.style.width = w + "px";
x.style.height = h + "px";
}
</script>
</body>
</html>