AngularJS - 居中图像的水平滚动条

时间:2015-02-18 16:07:13

标签: javascript html css angularjs

我有一张比屏幕大的图片,用户可以在图像上左右滚动。如何使用javascript或css水平居中图像?

以下是观点:

<div ng-show="isLandscape">
    <div ng-if="isSelected(color.code)" ng-repeat="color in colors">
    <img id="fullSwatch" ng-src="{{ images.swatches[color.code] }}" full-swatch>
    </div>
</div>

这是我的指示:

colorsController.directive('fullSwatch', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            element.bind('load', function() {

            var img = document.getElementById("fullSwatch");

            //swap width and height values because they are before orientation change
            var h = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
            var w = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);

            var imageWidth = img.width;
            var imageHeight = img.height;

            var aspectRatio = imageWidth / imageHeight;

            // fill image vertically
            imageHeight = h;
            imageWidth = h * aspectRatio;

            img.style.width = imageWidth + "px";
            img.style.height = imageHeight + "px";
            img.style.maxWidth = "none";

            var container = img.parentNode;
            var scrollLeft = (imageWidth - w) / 2;
            container.scrollLeft = scrollLeft;

        });
    }
};
});

我尝试将向左滚动添加到父div和图像本身,但它没有被应用。

1 个答案:

答案 0 :(得分:0)

div{
     position:relative;
     overflow-y:hidden;
}


   #fullSwatch{
     margin:0 auto;
    display:table;
}

我还使用Google Image制作了一个Jsfiddle演示示例 http://jsfiddle.net/x6jDu/ 这种方法非常简单,任何超过外部div的超大图像都将以水平滚动为中心。图像id上的自动边距为0自动执行居中技巧。希望这能解决你的问题。