首页 > 解决方案 > 是否有影响正文标签的字体大小滑块的解决方案,但只需要它来影响某些 css 类

问题描述

我有以下代码来更改body网站上的字体大小。它工作正常,但调整大小变得很糟糕,因为它会影响到正文中的每个文本。因此,我尝试将其转换为仅将字体调整大小应用于某些 css 类,但我找不到解决方案。我想做的是调整大小只会影响例如.content-block, .main-content, .etc,....

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="utf-8">
<link href="app.css" rel="stylesheet">
</head>

<body>
<div class="font-slider">
<input type="range" min="17" max="28" value="22" step="1"/>
</div>
<div>
<h1>Changing Font Size</h2>
<p>I am just a boring text, existing here solely for the purpose of this demo</p>
<p>And I am just another one like the one above me, because two is better than having only one</p>
<a href="#">I am a link, don't click me!</a>
</div>
<script>

var curSize = localStorage.getItem("saveSize");
var slider = document.querySelector('.font-slider input[type="range"]')
var body = document.body

if (curSize) {
var saveSize = curSize;
body.style.fontSize = saveSize + 'px';
}

slider.addEventListener("input", function (e) {
var newSize = this.value,
    defaultSize = body.style.getPropertyValue('font-size'),
    minSize = 17,
    maxSize = 28;

if (newSize <= maxSize && newSize >= minSize) {
    body.style.fontSize = newSize + 'px';

    localStorage.setItem("saveSize", newSize);
}
});
</script>
</body>
</html>

标签: javascripthtml

解决方案


您可以在需要的类中使用 css 变量,在 javascript 中只需更改该变量的值:

var curSize = null; // localStorage.getItem("saveSize");
var slider = document.querySelector('.font-slider input[type="range"]')
var body = document.body
var defaultSize = body.style.getPropertyValue('font-size');

if (curSize) {
  var saveSize = curSize;
  document.documentElement.style.setProperty("--font-size", saveSize + "px");
  //body.style.fontSize = saveSize + 'px';
}

slider.addEventListener("input", function(e) {
  var newSize = this.value,
    minSize = 17,
    maxSize = 28;

  if (newSize <= maxSize && newSize >= minSize) {
    document.documentElement.style.setProperty("--font-size", newSize + "px");
    //    body.style.fontSize = newSize + 'px';
    //    localStorage.setItem("saveSize", newSize);
  }
});
:root {
  --font-size: 1em;
}

.affected,
.dynamic {
  font-size: var(--font-size);
}


/* ignore this */

.affected:before,
.dynamic:before,
.content :not(.affected):not(.dynamic):before {
  content: "dynamic font size:";
  background-color: lightgreen;
  border: 1px solid grey;
  font-size: initial;
  margin: 1em;
  padding: 0.2em;
}

.content :not(.affected):not(.dynamic):before {
  content: "static font size:";
  background-color: pink;
}
<div class="font-slider">
  <input type="range" min="17" max="28" value="22" step="1" />
</div>
<div>
  <div class="content">
    <h1>Changing Font Size</h2>
      <p class="dynamic">I am just a boring text, existing here solely for the purpose of this demo</p>
      <p>And I am just another one like the one above me, because two is better than having only one</p>
      <a href="#" class="affected">I am a link, don't click me!</a>
  </div>
</div>


推荐阅读