AngularJS:尝试通过组合变量和"px"来创建样式值



我做了一个程序,允许用户在"白板"上写文本并实时改变颜色。 我现在也尝试让用户能够更改字体大小。 如何将"writing_size"变量与字符"px"组合以形成"font-size"的值?

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<title>AngularJS Whiteboard</title>
</head>
<body>
<div ng-app="">

<textarea name="message" rows="10" cols="30" ng-model="writing">
</textarea>
<span>    Marker color: <input type = "text" size = "7" ng-model="marker_color"></span>
<span>    Writing size: <input type = "text" size = "7" ng-model="writing_size"></span>
<br>
<br>
<div id = "whiteboard" ng-bind="writing" ng-style="{ color : marker_color, font-size: {{writing_size + 'px'}} }">   
</div>
<div id = "test">
{{ writing_size + "px"}}
</div>
</div>
</body>
</html>

第一个问题:font-size键不能在没有撇号的情况下使用,因为它不是有效的 JS Object 键。您需要写例如ng-style="{'font-size': '12px'}".

其次,ng-style属性被评估为 JS,因此不能使用双大括号语法,因为它不是有效的 JS。就像你在 JS:ng-style="{'font-size': writing_size + 'px'}"中一样写。

您的工作示例:

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<title>AngularJS Whiteboard</title>
</head>
<body>
<div ng-app="">
<textarea name="message" rows="10" cols="30" ng-model="writing">
</textarea>
<span>    Marker color: <input type = "text" size = "7" ng-model="marker_color"></span>
<span>    Writing size: <input type = "text" size = "7" ng-model="writing_size"></span>
<br>
<br>
<div id = "whiteboard" ng-bind="writing" ng-style="{ color : marker_color, 'font-size': writing_size + 'px' }">   
</div>
<div id = "test">
{{ writing_size + "px"}}
</div>
</div>
</body>
</html>

最新更新