javascript - 相对于当前 Div 的边距

标签 javascript jquery html css

因此,我正在通过编辑要移动的边距来尝试 jQuery 动画效果。问题是,当我使用动画效果时,它位于一个包含页面上大部分内容的 div 中。我正在编辑的边距最终是相对于实际页面的,而不是它所在的 div。这是一个示例:

<html>
<head>

<script src="javascript/jQuery-1.7.1.min.js" type="text/javascript"></script>

<style type="text/css">

#maincontent{
padding-bottom: 3em;
width: auto;
background:#fff;
text-align: left;
margin-left: 10%;
margin-right: 10%;
margin-top: 60px;
}

#animateBox
{
height: 100px;
width: 100px;
background: red;
position: absolute;
}

#moveLeft
{
display: none;
}

#moveRight
{
display: inline;
}

</style>

<script type="text/javascript">
$(document).ready(function() {
    $('#moveRight').click(function() {
        $("#animateBox").animate(
            {"left": "+=200px"},"normal");
            $('#moveRight').css('display', 'none');
            $('#moveLeft').css('display', 'inline');
    });

    $("#moveLeft").click(function() {
        $("#animateBox").animate(
            {"left": "-=200px"},
            "normal");
            $('#moveLeft').css('display', 'none');
            $('#moveRight').css('display', 'inline');

    });
});

</script>

</head>
<body>

<div id="maincontent">

<div id="animateBox"></div>

<br />
<br />
<br />
<br />
<br />

<input type="button" id="moveRight" Value="Move Right" style="width: 100px">
<input type="button" id="moveLeft" Value="Move Left" style="width: 100px">

</div>
</body>

有什么办法可以解决这个问题吗?谢谢。

最佳答案

在 css 中将 .maincontent 设置为 position:relative。

#maincontent{
padding-bottom: 3em;
width: auto;
background:#fff;
text-align: left;
margin-left: 10%;
margin-right: 10%;
margin-top: 60px;
position:relative /*Add this*/
}

关于javascript - 相对于当前 Div 的边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9451221/

相关文章:

javascript - 随机数生成器产生有偏差的结果 - 没有明确的原因

jquery - 模式中的 Symfony2 表单未处理

javascript - 如何使用 Javascript 禁用和启用按钮

javascript - Laravel 通过模态上传图片不起作用

php - 当仅为用户创建用户时,如何创建新文件夹

HTML/CSS : how to put all <li> in <ul> on the same line and centered

javascript - 如何在 html Canvas 中绘制细但更清晰的线条?

javascript - 具有重复条目的数组问题

javascript - 浏览器刷新后滚动到特定的垂直位置

javascript - 可重用性 : how to use same list items at different places in a web page