1

我想将图像居中在div. 我的代码是,

<html>
<head>
    <title>test</title>
    <style type="text/css">
        .wrapper { 
            background:#EFEFEF; 
            margin: auto; 
            position: relative;
            margin-bottom: 20px !important;
            width: 800px;
            padding-top: 5px;
        }
        .scrolls { 
            overflow-x: scroll;
            overflow-y: hidden;
            height: 400px;
        } 
        .imageDiv { 
            margin: 0;
            height: 400px;
        } 
        .imageDiv img { 
            max-height: 400px;
            cursor: pointer;
            margin-left:20px;
        }
    </style>
    <script type="text/javascript" src="jquery-latest.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            var wh=$(window).height()/4;
            $('.wrapper').css('margin-top',wh);
        });
        $(window).load(function(){
            var tw = 0;
            $.each($('.imageDiv img'), function() {
                tw += $(this).width();
            });
            $('.imageDiv').width(tw);
            $('.imageDiv img').click(function(){
                var imgid=$(this).attr('id');
                var width = $(imgid).width();
                var margin = width/2;
                $(imgid).css("margin-left","-"+margin);
            });
        });
    </script>
</head>
<body>
    <div class="wrapper">
        <div class="scrolls">
            <div class="imageDiv">
                    <img src="001_19_3.jpg" id="img1"/>
                    <img src="002_21_3.jpg" id="img2"/>
                <img src="003_19_3.jpg" id="img3"/>
                <img src="004_19_3.jpg" id="img4"/>
                <img src="005_15_3.jpg" id="img5"/>
                <img src="NB_1a_3.jpg"  id="img6"/>
                <img src="NB_2_3.jpg"   id="img7"/>
                <img src="NB_3_3.jpg"   id="img8"/>
            </div>
        </div>
    </div>
</body>

如果我单击滑块中的图像,该图像应该转到 div 的中心。并且滚动条也想根据图像的位置移动。任何人都可以帮忙吗?请!

4

1 回答 1

1

尝试这个:

$('.imageDiv img').click(function() {
    var imgid = $(this).attr('id');
    var width = $(imgid).width();
    var margin = width / 2;

    var cssObj = {
        'margin-left': '-' + margin,
        'position': 'absolute',
        'left': '50%'
    }

    $(imgid).css(cssObj);
});
于 2012-12-27T11:49:45.607 回答