对角放置HTML元素

时间:2011-02-28 00:31:25

标签: javascript html positioning

我是Javascript&的新手相对较新的HTML。我想知道我应该使用什么语言(纯HTML或Javascript和html)&一些算法的建议,以便做到以下几点:

在背景上放置4个方格,但将它们对角放置。每个方块都是一个链接,您可以单击该链接转到其他页面。 那么我如何才能像对照下面的对象那样对角放置html元素呢?

http://i54.tinypic.com/2v7uw5u.png

我相信我的代码看起来像这样:

<script>
    function positionIt()
    {
        var screenW = // javascript function to get screen width??;
        var screenH = // javascript function to get screen height??;

        var sq1 = document.getElementById( "square1" );
        var sq2 = document.getElementById( "square2" );
        var sq3 = document.getElementById( "square3" );
        var sq4 = document.getElementById( "square4" );

        // What javascript functions set a elements x,y positions?
        // Should I use another way of positioning the square (not by absolute terms)
        sq1.setXPos( screenW / 4 );
        sq1.setYPos( screenH / 4 );

        sq2.setXPos( screenW / 3 );
        sq2.setYPos( screenH / 3 );
    }
</script>

// OR if I use css
.menu { background-color: blue; }
/* Position the square in absolute terms diagonally */
#square1 { x=200; y=200; }
#square2 { x=300; y=300; }
#square3 { x=400; y=400; }
#square4 { x=500; y=500; }

<div class="menu" onload="positionIt()">
    <a id="square1" href="home.html"><img src="square.jpg" /></a>
    <a id="square2" href="home.html"><img src="square.jpg" /></a>
    <a id="square3" href="home.html"><img src="square.jpg" /></a>
    <a id="square4" href="home.html"><img src="square.jpg" /></a>
</div>

2 个答案:

答案 0 :(得分:4)

您可以使用绝对定位。

在CSS中:

#menu {
    position: relative;
    width: /*enough width for all of the positioned elements*/
    height: /*enough height for all of the position elements*/
}
#squareN {
    top: /*how far from top of #menu*/
    left: /*how far from left of #menu*/
    position: absolute;
    width: /*as required*/
    height: /*as required*/
}

答案 1 :(得分:1)

Live Demo
Live Demo(已更改left属性订单以匹配您的模型)

我试着记住你要求的数字。

<强> HTML:

<div class="menu">
    <a id="square1" href="home.html"><img src="http://dummyimage.com/100/f90/fff" /></a>
    <a id="square2" href="home.html"><img src="http://dummyimage.com/100/f90/fff" /></a>
    <a id="square3" href="home.html"><img src="http://dummyimage.com/100/f90/fff" /></a>
    <a id="square4" href="home.html"><img src="http://dummyimage.com/100/f90/fff" /></a>
</div>

<强> CSS:

.menu {
    background: blue;
    width: 800px;
    height: 800px;
    position: relative
}
/* Position the square in absolute terms diagonally */
#square1 { position:absolute; left:200px; top:200px; }
#square2 { position:absolute; left:300px; top:300px; }
#square3 { position:absolute; left:400px; top:400px; }
#square4 { position:absolute; left:500px; top:500px; }

这是如何工作的?请参阅:http://css-tricks.com/absolute-positioning-inside-relative-positioning/