简体   繁体   English

如何更改背景元素位置?

[英]How to change background element position?

What I have right now only moves image for second then goes back to orginal position? 我现在所拥有的只是将图像移动第二个然后又回到原始位置?

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <link rel="stylesheet" type="text/css" href="styles/formstyle.css"/> 
    <script type="text/javascript">

     function northwest(image) {

       var myElement;//create reference
       myElement = document.getElementById('image').style;
       myElement.top = "50px";
       myElement.left = "50px";
     }

    function northeast(image) {
       var myElement;//create reference
       myElement = document.getElementById('image').style;
       myElement.top = "14px";
       myElement.left = "1106px";
    }

    <title>Move It!</title>

</head>

<body>  
     <div id = "para">
        Blah Blah Blah Blah:)     </div>

     <div id ="image" ></div>

    <div id = "links">
    <form action = " ">
    <p >
        <a href="javascript: northwest('image')">move background image to the northwest</a>
        <a href="javascript: northeast('image')">move background image to the northeast</a>
        <a href="javascript: southwest('image')">move background image to the southwest</a>
        <a href="javascript: southwest('image')">move background image to the southwest</a>
    </p> 
    </form>   
</div>
</body>
</html>

CSS CSS

#image {
        background-image:url('http://nova.umuc.edu/~ct386a28/lovej2ee/exercise4/images/kito.jpg');
        background-repeat: no-repeat;
        position: absolute; 
        top: 205px; 
        left: 456px; 
        color: inherit;
        width: 133px;
        height: 107px;
        filter:alpha(opacity=60);
        opacity:0.6;            
        } 

  #para {
        text-align: left;
        font-family: Arial;
        position: relative; 
        top: 73px; 
        left: 447px; 
        color: inherit;
        width: 132px;
        height: 341px;
        } 

You have this function attached to submit buttons. 您已将此功能附加到提交按钮。 So you are submitting the form each time, essentially refreshing the page. 因此,您每次都要提交表单,基本上刷新页面。

Consider making these anchors or buttons instead of submit. 考虑制作这些锚点或按钮而不是提交。 If you want to use submit, you need to stop the default behavior . 如果要使用submit,则需要停止默认行为

Another problem is that you retreive from the DOM before it is even loaded. 另一个问题是你甚至在加载之前就从DOM中撤回了。 Try putting the JavaScript on the bottom of the HTML file right before the closing body-tag. 尝试将JavaScript放在关闭body标记之前的HTML文件的底部。 This is considered best-pratice by Google and Yahoo!. 这被谷歌和雅虎认为是最佳实践!

Yet another problem I see is the way you retreive the DOM element. 我看到的另一个问题是你检索DOM元素的方式。

I would do it like this: 我会这样做:

var myElement; // creating a reference
myElement = document.getElementById("image"); // initialize the reference

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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