我想动态更新字体大小,所以我创建了这段代码,但问题是它不起作用。
var font_size = 36;
$('#content').on('click', function(){
$('#editor').css('display', 'block');
var numbersValue = "<input type=\"number\" id=\"input-fz\" value="+font_size+">";
var currentValue = $(numbersValue).prop('value');
var eleId = $(numbersValue).prop('id');
$(eleId).change(function(event) {
/* Act on the event */
newValue = $(this).val();
newvalueFonts = newValue;
$('h1').css('font-size', newvalueFonts);
});
$('#result').html(numbersValue)
})
最佳答案
可能需要三个改变
- 使用
#
作为id选择器; - 将事件从 body 委托(delegate)给 input 元素。
- 为字体大小添加一个单位,如
px
var font_size = 36;
$('#content').on('click', function() {
$('#editor').css('display', 'block');
var numbersValue = "<input type=\"number\" id=\"input-fz\" value=" + font_size + ">";
var currentValue = $(numbersValue).prop('value');
var eleId = $(numbersValue).prop('id');
// Implementing point 1,2
$('body').on('change', '#' + eleId, function(event) {
/* Act on the event */
newValue = $(this).val();
newvalueFonts = newValue;
// implementing point 3
$('h1').css('font-size', newvalueFonts + 'px');
});
$('#result').html(numbersValue)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 id="content">
Some Content Here
</h1>
<div id="editor" style="display:none">
<div id="result"></div>
</div>
关于javascript - 如何使用 jquery 动态更新字体大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44690150/