如何更改背景元素位置?

时间:2011-03-26 02:15:54

标签: javascript css xhtml

我现在所拥有的只是将图像移动到秒,然后回到原始位置?

<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

#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;
        } 

2 个答案:

答案 0 :(得分:1)

您已将此功能附加到提交按钮。因此,您每次都要提交表单,基本上刷新页面。

考虑制作这些锚点或按钮而不是提交。如果您想使用提交,则需要停止default behavior

答案 1 :(得分:1)

另一个问题是你在加载之前就从DOM中撤回了。尝试将JavaScript放在关闭body标记之前的HTML文件的底部。这被谷歌和雅虎认为是最佳实践!

我看到的另一个问题是你检索DOM元素的方式。

我会这样做:

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