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

自定义Like Button点赞状态无法正常显示问题求助

Tumblr自定义点赞按钮无法显示点赞状态的解决方法

问题根源

你的代码存在两个核心问题:

  1. HTML结构嵌套错误,原生点赞按钮没绑定到触发容器上,状态变化无法传递
  2. 缺少同步点赞状态的JavaScript逻辑,没法根据原生按钮的状态更新自定义按钮样式

修正后的完整代码

HTML

<center>
  <div class="custom-like-button">
    <div class="like_button">
      {LikeButton} <!-- 把原生按钮放到触发容器内 -->
    </div>
    <span class="our_button">♥</span>
  </div>
</center>

CSS

.custom-like-button {
  position: relative;
  display: block;
  width: 40px;
  height: 40px;
  cursor: pointer;
}
.like_button {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  z-index: 10;
}
.like_button iframe {
  width: 100% !important;
  height: 100% !important;
}
.our_button {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  transition: color 0.2s;
}
.like_button:hover ~ .our_button {
  color: red;
}
.like_button.liked ~ .our_button {
  color: red;
}

JavaScript(必须添加)

// 监听Tumblr点赞事件
document.addEventListener('DOMContentLoaded', function() {
  // 遍历所有自定义点赞容器
  document.querySelectorAll('.custom-like-button').forEach(function(container) {
    const likeBtn = container.querySelector('.like_button');
    const iframe = likeBtn.querySelector('iframe');
    
    // 监听iframe的消息,同步状态
    window.addEventListener('message', function(e) {
      if (e.data && e.data.tumblrLikeButton) {
        const { liked, postId } = e.data.tumblrLikeButton;
        // 匹配当前按钮对应的文章ID
        if (iframe.src.includes(postId)) {
          if (liked) {
            likeBtn.classList.add('liked');
          } else {
            likeBtn.classList.remove('liked');
          }
        }
      }
    });

    // 初始化时检查初始点赞状态
    const checkInitialState = () => {
      if (iframe.contentWindow) {
        iframe.contentWindow.postMessage({ tumblrLikeButton: 'getState' }, '*');
      }
    };
    // 等待iframe加载完成
    iframe.addEventListener('load', checkInitialState);
    // 兼容加载慢的情况
    setTimeout(checkInitialState, 1000);
  });
});

修改说明

  1. HTML结构修正:把原生{LikeButton}放到.like_button容器内,清理多余未闭合标签,确保层级正确
  2. CSS调整:给.our_button添加居中样式,将+选择器改为~(适配容器内的原生按钮层级),保证样式触发逻辑正常
  3. 添加JS逻辑:通过监听Tumblr点赞按钮的跨域消息,同步自定义按钮的liked类,实现点赞状态的实时更新,同时初始化时会检查已点赞的历史状态

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 11:25:10