我希望使用按钮来更改常见DIV的字体系列。 许多解决方案都有 javascript 函数中列出的字体,但我们在字体产品页面上提供字符映射,因此需要在 HTML 中指定字体。
这是 HTML:
<button onclick="changeFont('Font 1'); ">Font 1</button>
<button onclick="changeFont('Font 2'); ">Font 2</button>
<button onclick="changeFont('Font 3'); ">Font 3</button>
<div class="character-map" style="font-size: 36pt;">Text</div>
这是javascript:
<script>
function changeFont(font){
document.getElementById("character-map").style.fontFamily = font.value;
}
</script>
如果您有任何问题,请告诉我,很乐意为您提供帮助。
担
onclick="changeFont('Font 1')
你用参数调用方法"changeFont":"字体 1" - 字符串。 在方法changeFont(font)
中,必须使用参数font
(其字符串 - "字体 1"( 但是你写font.value
.字符串没有值。 所以,写这个的正确方法
function changeFont(font){
document.getElementById("character-map").style.fontFamily = font
function changeFont(font){
let el = document.querySelector(".character-map")
el.style.fontFamily = font;
}
<button onclick="changeFont('Georgia, serif'); ">Font 1</button>
<button onclick="changeFont('Gill Sans, sans-serif'); ">Font 2</button>
<button onclick="changeFont('cursive'); ">Font 3</button>
<div class="character-map" style="font-size: 36pt;">Text</div>
最后。请阅读有关在 DOM 中捕获节点的信息。您尝试getElementById
但您的元素没有 id,只有class="character-map"
所以我发现有三件事可能是问题所在
- 在changeFont函数中,你只需要使用font而不是font.value
- 您需要将字符映射指定为 DIV 属性而不是类,因为类选择器可能会返回多个节点作为结果,如果我们只针对 UI 中的特定节点,最好使用 ID 选择器 字体
- 值应为有效的字体系列,以反映在 UI 中。
请参考以下内容
<button onclick="changeFont('serif'); ">Font 1</button>
<button onclick="changeFont('Cursive'); ">Font 2</button>
<button onclick="changeFont('fantasy'); ">Font 3</button>
<div id="character-map" class="character-map" style="font-size: 36pt;">Text</div>
function changeFont(font){
document.getElementById("character-map").style.fontFamily=font;
}