You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在HTML中自动重复背景文本?现有代码无法运行求解决

你的水印代码失效原因及修复方案

Hey there! Let's break down why your watermark code isn't working and get it up and running smoothly.

问题根源

The core issue is execution timing. Your script runs before the DOM (the HTML elements) have fully loaded. When the <script> tag fires, the .watermarked div hasn't been rendered yet—so document.querySelectorAll('.watermarked') returns an empty list. That means your code never updates the data-watermark attribute, leaving the CSS pseudo-element with no content to display. No content = no watermark!

修复方法

You have two simple ways to fix this:

方法1:把脚本移到DOM元素之后

Just move your <script> tag to after the .watermarked div. This way, when the script runs, the target element already exists in the DOM. Here's the full working code:

<style>
.watermarked { position: relative; overflow: hidden; }
.watermarked img { width: 100%; }
.watermarked::before { 
  position: absolute; 
  top: -75%; 
  left: -75%; 
  display: block; 
  width: 150%; 
  height: 150%; 
  transform: rotate(-45deg); 
  content: attr(data-watermark); 
  opacity: 0.7; 
  line-height: 3em; 
  letter-spacing: 2px; 
  color: #fff; 
}
</style>
<div class="watermarked" data-watermark="howbloggerz">
<img src="http://www.w3schools.com/css/img_fjords.jpg">
</div>
<script>
Array.from(document.querySelectorAll('.watermarked')).forEach(function(el) { 
  el.dataset.watermark = (el.dataset.watermark + ' ').repeat(300); 
});
</script>

方法2:用DOMContentLoaded事件包裹脚本

If you prefer to keep your script in its original position, wrap it in a DOMContentLoaded listener. This ensures the code only runs once the entire DOM is ready:

document.addEventListener('DOMContentLoaded', function() {
  Array.from(document.querySelectorAll('.watermarked')).forEach(function(el) { 
    el.dataset.watermark = (el.dataset.watermark + ' ').repeat(300); 
  });
});

生效效果

After applying either fix, the script will successfully update the data-watermark attribute with 300 repetitions of your text (plus spaces). The CSS will then use this value to render a tiled, diagonal watermark over your image—you'll see "howbloggerz" repeated across the photo with 70% opacity, just like you intended.

内容的提问来源于stack exchange,提问作者Willy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:50:06