我正在尝试在html页面上提供一个可以放大和缩小文本的功能。
我已经尝试使用所有可用的浏览器。这是我的代码:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#zoomtext
{
transform: scale(1);
transition: transform 0.2s ease-in-out;
}
</style>
<script>
window.addEventListener("load", function()
{
var zoom = 1;
var zoomStep = 0.2;
});
document.getElementById("zoomIn").addEventListener("click",function(){zoom += zoomStep; document.getElementById("zoomtext").style.transform = "scale("+zoom+")";});
document.getElementById("zoomOut").addEventListener("click",function(){if(zoom > zoomStep){zoom -= zoomStep; document.getElementById("zoomtext").style.transform = "scale("+zoom+")";}});
</script>
</head>
<body>
<button id="zoomOut">-</button>
<button id="zoomIn">+</button>
<article>
<section id="zoomtext">
<p>This is a text that I want to be able to zoom in and out by means of the two buttons indicating plus and minus.</p>
</section>
</article>
</body>
</html>
没有错误信息。点击没有任何反应。
答案 0 :(得分:1)
script
的末尾添加body
zoom, zoomStep
变量
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#zoomtext {
transform: scale(1);
transition: transform 0.2s ease-in-out;
}
</style>
</head>
<body>
<button id="zoomOut">-</button>
<button id="zoomIn">+</button>
<article>
<section id="zoomtext">
<p>This is a text that I want to be able to zoom in and out by means of the two buttons indicating plus and minus.</p>
</section>
</article>
<script>
var zoom = 1;
var zoomStep = 0.2;
document.getElementById("zoomIn").addEventListener("click", function() {
zoom += zoomStep;
document.getElementById("zoomtext").style.transform = "scale(" + zoom + ")";
});
document.getElementById("zoomOut").addEventListener("click", function() {
if (zoom > zoomStep) {
zoom -= zoomStep;
document.getElementById("zoomtext").style.transform = "scale(" + zoom + ")";
}
});
</script>
</body>
</html>
答案 1 :(得分:1)
您的代码存在的问题是zoom
和zoomStep
从未被评估。第一个事件侦听器只是创建一个函数,但永远不会执行其中的代码。
在此处查看有效代码:https://codepen.io/marc-simplon/pen/vqYwYQ?editors=1010
答案 2 :(得分:0)
如果您需要设置整个窗口的缩放比例,那么在没有外部插件的情况下可能无法实现(请参见Changing the browser zoom level)
如果要专门为#zoomtext元素设置缩放比例,可以使用“ zoom” CSS属性(https://developer.mozilla.org/en-US/docs/Web/CSS/zoom),但这不是标准的。解决此问题的另一种方法是增加或减少#zoomtext元素上的font-size CSS属性:
document.getElementById("zoomtext").style.fontSize = '12px'