如何使用滑块更改文本大小?

Sim*_*ely 1 html css jquery

我正在尝试编写一些代码来使用滑块动态更改文本的大小,但是它不起作用。

$('input').on('change', function() {
  var v = $(this).val();
  $('.userText p').css('font-size', v + 'em')
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="range" min="1.2" max="2.6" step=".2" id="slider" />
<div class="userText">
  <p>Some text that should dynamically change size</p>
</div>
Run Code Online (Sandbox Code Playgroud)

有人可以在这里提供任何建议吗?

obs*_*ure 5

平变化为您松开鼠标按钮事件将立即启用。您想要的是oninput事件,该事件将在您移动滑块时立即触发。

$('input').on('input', function() {
  var v = $(this).val();
  $('p').css('font-size', v + 'em')
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="range" min="1.2" max="2.6" step=".2" id="slider" />

<p>Some text that should dynamically change size</p>
Run Code Online (Sandbox Code Playgroud)


leo*_*ess 5

只需添加input为事件,因为change仅在释放鼠标时触发。为了更好的可用性,我还添加了更小的步长和 min 的起始值。

document.querySelector('input').addEventListener('input', e => document.querySelector('p').style.fontSize = e.target.value + 'em');
Run Code Online (Sandbox Code Playgroud)
<input type="range" value="1.2" min="1.2" max="2.6" step=".0002" id="slider" />
<p>Some text that should dynamically change size.</p>
Run Code Online (Sandbox Code Playgroud)

有关不同浏览器之间差异的更多信息,请参阅在 Firefox 中拖动时不会触发 input type=range 上的 onchange 事件

jQuery:

$('input').on('input', e => $('p').css('font-size', $(e.target).val() + 'em'));
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="range" value="1.2" min="1.2" max="2.6" step=".0002" id="slider" />
<p>Some text that should dynamically change size.</p>
Run Code Online (Sandbox Code Playgroud)