动态更改class属性

时间:2018-01-09 08:56:20

标签: html css angularjs

当我使用margin-top动态设置图像时,我的图像没有到达正确的位置。

请参阅下图中指向右侧的红色箭头(红色),这就是我想要的:

enter image description here

我有以下css:

.file_arrow_right {
        background: url('../images/right_icon.png') no-repeat;
        cursor: pointer;
        width: 35px;
        height: 22px;
        background-size: 18px;
        background-position: 0px;
        margin-top: -500px;
    }

我想根据特定的图片高度动态更改上面的margin-top,所以我使用了以下内容 -

app.controller('filePreviewSectionCtrl', 
function ($scope, $q, $sce, $rootScope, $filter, $compile, $timeout, $state, 
$modalInstance, commFile, blobUrl) {    
    var myBase64 = "data:"+commFile.fileType+";base64,"+commFile.image+"";
    //jpeg, .jpg, .bmp, .png, .txt
    if(commFile.fileType.split("/")[1] == "jpeg" || 
     commFile.fileType.split("/")[1] == "jpg" ||  
     commFile.fileType.split("/")[1] == "bmp" || 
     commFile.fileType.split("/")[1] == "png") {
        $scope.imgBlob = myBase64;

        var img = new Image();
        img.src = myBase64;
        img.addEventListener('load',function(){
            var width=img.width;
            var height=img.height;
            console.log("width: "+width);
            console.log("height: "+height);
            // should change dynamically
            $scope.arrowMarginTop = "margin-top: "+height/2+"px";
        });     
    } 
})

这是HTML:

       <script type="text/ng-template" id="filePreviewSectionCtrl.html">
        <div id="dynamicFile" style="width:100%; height:100%;">
            <span class= "file_arrow_right" ng-class="arrowMarginTop">
            </span>     
        </div>          
       </script>

更新

根据@Temani给出的建议,span已经是内联元素,并且它不会对margin-top产生任何影响,我将span更改为div。然后我使用@Satpal答案动态更改CSS。

1 个答案:

答案 0 :(得分:0)

在范围变量arrowMarginTop中指定CSS规则时,您需要使用ngStyle directive而不是ngClass

<span class= "file_arrow_right" ng-style="arrowMarginTop">
        </span> 

同时设置对象

$scope.arrowMarginTop = { "margin-top" : height/2 + "px" };
相关问题