jQuery改变图像位置

时间:2012-01-31 13:55:42

标签: jquery

我是jQuery的新手,我需要你的帮助。

我想构建一个包含2列标记为X和Y的表,每列中的输入字段和一个更改按钮,当用户单击按钮时,jQuery函数将检查字段是否为空,如果它们是函数将将默认值放在jquery标头中定义的偏移量({left:x,top:y})中,如果字段不为空,则会从字段中获取值并更改图像的位置。

因此,每次用户更改字段的值时,图像的位置都会改变。

提前完成,

2 个答案:

答案 0 :(得分:1)

这是一个带有工作版本的JS小提琴:http://jsfiddle.net/UKRD8/14/

输入输入数字后,请确保输入'px'。

答案 1 :(得分:0)

    <div style="position:relative; width:100%; height:100%;">
    <table cellpadding="0" cellspacing="0" style="position:relative; z-index:9;">
        <tr>
            <td>X:</td>
            <td>
                <input id="txtX" type="text" /></td>
        </tr>
        <tr>
            <td>Y:</td>
            <td>
                <input id="txtY" type="text" /></td>
        </tr>
        <tr>
            <td colspan="2">
                <input id="btnUpdate" type="button" value="Update" onclick="updateCords()" /></td>
        </tr>
    </table>

    <img id="img" src="http://upload.wikimedia.org/wikipedia/commons/thumb/8/85/Smiley.svg/160px-Smiley.svg.png" style="position:absolute; z-index:1;" />
  </div>  

<script>
    function updateCords() {
        var x = $('#txtX').val();
        var y = $('#txtY').val();

        if (x === '') { x = 0 }
        if (y === '') { y = 0 }

        $('#img').css({ 'left': x + 'px', 'top': y + 'px' });
    }
</script>
相关问题