首页 > 解决方案 > 当元素在视图中时更改边框半径 - 如何将百分比更改为像素

问题描述

我找到了一些代码,它们会在滚动时改变我的 div 的边框半径。它有效,但它是一个百分比,而不是一个像素。

var hHeight = $("html").height(),
    radius  = 10;

$(window).scroll(function() {
  var scrollTop = $(window).scrollTop(),
      percentage   = 0 + ((1*scrollTop)/hHeight) * 2;
  $(".video_content").css("border-radius", percentage + "%");
});

当这个 div 在视图中时,我希望边框半径从 0px 变为 10px。我已经调整了很多,但还没有成功。

这是我开始使用的代码笔: https ://codepen.io/yy/pen/ByrMZR

任何帮助将非常感激!

标签: javascriptcssscroll

解决方案


在您非常具体的情况下(0到10),您可以使用该百分比并将其除以10。

稍微调整一下,让你倒退:从 0 到 10,而不是像现在这样从 100 到 0

var hHeight = $("html").height(),
    radius  = 0;

$(window).scroll(function() {
  var scrollTop = $(window).scrollTop(),
      percent   = 0 + ((100*scrollTop)/hHeight) * 2;
  $(".round").css("border-radius", percent/10 + "px");
});
html {
  position: relative;
  width: 100%;
  height: 200%;
  background: #333;
}
.round {
  position: fixed;
  width: 100%;
  height: 100%;
  left: 0;
  top: -50%;
  background: #f7f7f7;
  border-radius: 0%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="round"></div>


推荐阅读