如何使用JS在HTML页面上打开字体对话框(类似↓)?

感谢帮助。

最佳答案

JavaScript中没有这样的命令,但是您可以创建自己的小字体选择器。
这是示例:



function updateh1family() {
  var selector = document.getElementById('selecth1FontFamily');
  var family = selector.options[selector.selectedIndex].value;
  var h1 = document.getElementById('text')
  h1.style.fontFamily = family;
}

function updateSize() {
  document.getElementById('text').style.fontSize = document.getElementById('size').value + "px";
}

function updateColor() {
  document.getElementById('text').style.color = document.getElementById('color').value;
}

<!DOCTYPE html>
<html>

<head>
</head>

<body>
  <font id="text" style="font-size:30px;">Some text</font><br>
  <select id="selecth1FontFamily" name="selectFontFamily" onchange="updateh1family();">
    <option> Serif </option>
    <option> Arial </option>
    <option> Sans-Serif </option>
    <option> Tahoma </option>
    <option> Verdana </option>
    <option> Lucida Sans Unicode </option>
  </select>
  <input type="number" id="size" min="0" max="70" value="30" onchange="updateSize()" />
  <input type="color" onchange="updateColor()" id="color" />
</body>

</html>





您甚至可以使它看起来像是使用jQuery的对话框:
https://jqueryui.com/dialog/



function updateh1family() {
  var selector = document.getElementById('selecth1FontFamily');
  var family = selector.options[selector.selectedIndex].value;
  var h1 = document.getElementById('text')
  h1.style.fontFamily = family;
}

function updateSize() {
  document.getElementById('text').style.fontSize = document.getElementById('size').value + "px";
}

function updateColor() {
  document.getElementById('text').style.color = document.getElementById('color').value;
}

function showDialog() {
  $("#dialog").dialog();
}

<!DOCTYPE html>
<html>

<head>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Dialog - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

</head>

<body>
  <button onclick="showDialog()">open dialog</button>
  <div id="dialog" style="display:none;">
    <font id="text" style="font-size:30px;">Some text</font><br>
    <select id="selecth1FontFamily" name="selectFontFamily" onchange="updateh1family();">
    <option> Serif </option>
    <option> Arial </option>
    <option> Sans-Serif </option>
    <option> Tahoma </option>
    <option> Verdana </option>
    <option> Lucida Sans Unicode </option>
  </select>
    <input type="number" id="size" min="0" max="70" value="30" onchange="updateSize()" />
    <input type="color" onchange="updateColor()" id="color" />
  </div>
</body>

</html>

09-10 12:36
查看更多