将div的宽度设置为'显示宽度'一个没有宽度属性的div

时间:2015-12-13 01:25:10

标签: javascript jquery css angularjs

我使用ng-model将输入值绑定到.one的内容。我已设置.one设置绝对位置且未设置宽度,因此.one将水平扩展以适合内容。一切正常。

现在我要做的是将.two的宽度设置为等于.one的宽度,以便.two的宽度作为内容更改已添加到.one

以下工作没有成功,我相信因为.one没有宽度属性:

var x = $(".one").width()

$(".two").css("width", x + "px")

是否可以显示.one的宽度,而不是基于它的CSS宽度属性?

检查出来:FIDDLE

2 个答案:

答案 0 :(得分:2)

您可以将更新绑定到输入框上的keyup事件。

$('#input').keyup(function() {
    // Get the width of .one
    var oneWidth = $(".one").width();
    // Set the width of .two to the value stored in oneWidth
    $(".two").width(oneWidth);
});

答案 1 :(得分:0)

您可以使用指令ngKeyUp

  <input ng-model="text" ng-keyup="update()" />

这是在角色中绑定 keyup 事件的正确方法。

https://jsfiddle.net/alvarojoao/kstmua9e/1/

var app = angular.module("turingApp", []);

app.controller("turingController", ["$scope", function($scope) {

  $scope.update = function() {
    var oneWidth = $(".one").width();
    $(".two").width(oneWidth);
  };
}]);
.one {
  position: absolute;
  background-color: orange;
  height: 20px;
}

.two {
  background-color: green;
  height: 20px;
  width: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body ng-app="turingApp" ng-controller="turingController">

  <input ng-model="text" ng-keyup="update()" />

  <div class="one">{{text}}</div>

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

  <div class="two"></div>

</body>