简体   繁体   中英

positioning background image of div using javascript

I am trying to make a clipping window but it is not happening, here is the code sample:

<html>
<head>
    <style>
        #clippingWindow
        {
            height:178px;
            width:278px;
            overflow: hidden;
        }
        #bgImg
        {
            left:35px;
            border:54px;
        }
    </style>
    <script language="javascript">

        function getImgSize()
        {

            var ds = document.getElementsByName('a');
            var wid = ds[0].width;
            var pos = (wid-278)/2;

            alert(pos);
            alert(ds[0].id);

            if(ds[0].width>278)
            {
                dt.style.left=500; //this is not working
            }
        }
    </script>
</head>
<body><input type="button" onClick="getImgSize();">
    <div id="clippingWindow">
        <img name="a" src="sss.bmp" id="bgImg">
    </div><br><br><br>
    <div id="ad">
        <img name="a" src="484.jpeg">
    </div>
</body>
</html>

You probably need to set the position property of the element you want to position to something like absolute or relative (eg ds.style.position = "relative"; ). The left property doesn't have any effect on statically positioned elements.

Also, you probably need to use "500px" instead of the number 500 .

I see three issues:

  1. dt.style.left=500; should be ds.style.left=500; (but see point #3) ds.style.left=500; (but see point #3)
  2. You need to position your #bgImg element. Ex: position:relative;
  3. Most browsers should be OK with your 500 unit in the line ds.style.left=500; however dts.style.left='500px'; would be better.

jsFiddle example

您必须将css属性“ left”设置为一个值和一个度量值,例如“ 500px”(您忘了px)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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