javascript - 使用 JavaScript 在特定 div 上添加点击事件

标签 javascript jquery html css

我在 JavaScript 中有一个降雪效果,我想在掉落的第 10 片雪花上创建一个点击事件。我还想添加一个表示“可点击”的类。我们希望实现这一点,因此如果用户仅单击第 10 片雪花,那么他们将被重定向到奖品(我们还想添加一个类,以便我们可以通过 CSS 很好地设计它)。

我必须承认,我的 JavaScript 知识不如我的 jQuery 那么强,所以有人可以帮忙吗?这是我正在使用的代码笔:-

https://codepen.io/scottYg55/pen/GRRzOgO

#snowflakeContainer {
  position: absolute;
  left: 0px;
  top: 0px;
  bottom: 0;
  right: 0;
  background-color: #2c3e50;
}

.snowflake {
    padding-left: 15px;
    font-family: Cambria, Georgia, serif;
    font-size: 14px;
    line-height: 24px;
    position: fixed;
    color: #FFFFFF;
    user-select: none;
    z-index: 1000;
}

<div id="snowflakeContainer">
    <p class="snowflake">*</p>
</div>

JS

// The star of every good animation
var requestAnimationFrame = window.requestAnimationFrame || 
                            window.mozRequestAnimationFrame || 
                            window.webkitRequestAnimationFrame ||
                            window.msRequestAnimationFrame;

var transforms = ["transform", 
                  "msTransform", 
                  "webkitTransform", 
                  "mozTransform", 
                  "oTransform"];

var transformProperty = getSupportedPropertyName(transforms);

// Array to store our Snowflake objects
var snowflakes = [];

// Global variables to store our browser's window size
var browserWidth;
var browserHeight;

// Specify the number of snowflakes you want visible
var numberOfSnowflakes = 50;

// Flag to reset the position of the snowflakes
var resetPosition = false;

//
// It all starts here...
//
function setup() {
  window.addEventListener("DOMContentLoaded", generateSnowflakes, false);
  window.addEventListener("resize", setResetFlag, false);
}
setup();

//
// Vendor prefix management
//
function getSupportedPropertyName(properties) {
    for (var i = 0; i < properties.length; i++) {
        if (typeof document.body.style[properties[i]] != "undefined") {
            return properties[i];
        }
    }
    return null;
}

//
// Constructor for our Snowflake object
//
function Snowflake(element, radius, speed, xPos, yPos) {

  // set initial snowflake properties
    this.element = element;
    this.radius = radius;
    this.speed = speed;
    this.xPos = xPos;
    this.yPos = yPos;

  // declare variables used for snowflake's motion
    this.counter = 0;
    this.sign = Math.random() < 0.5 ? 1 : -1;

  // setting an initial opacity and size for our snowflake
    this.element.style.opacity = .1 + Math.random();
    this.element.style.fontSize = 12 + Math.random() * 50 + "px";
}

//
// The function responsible for actually moving our snowflake
//
Snowflake.prototype.update = function () {

  // using some trigonometry to determine our x and y position
    this.counter += this.speed / 5000;
    this.xPos += this.sign * this.speed * Math.cos(this.counter) / 40;
    this.yPos += Math.sin(this.counter) / 40 + this.speed / 30;

  // setting our snowflake's position
    setTranslate3DTransform(this.element, Math.round(this.xPos), Math.round(this.yPos));

    // if snowflake goes below the browser window, move it back to the top
    if (this.yPos > browserHeight) {
      this.yPos = -50;
    }
}

//
// A performant way to set your snowflake's position
//
function setTranslate3DTransform(element, xPosition, yPosition) {
  var val = "translate3d(" + xPosition + "px, " + yPosition + "px" + ", 0)";
    element.style[transformProperty] = val;
}

//
// The function responsible for creating the snowflake
//
function generateSnowflakes() {

  // get our snowflake element from the DOM and store it
    var originalSnowflake = document.querySelector(".snowflake");

    // access our snowflake element's parent container
    var snowflakeContainer = originalSnowflake.parentNode;

    // get our browser's size
  browserWidth = document.documentElement.clientWidth;
    browserHeight = document.documentElement.clientHeight;

    // create each individual snowflake
    for (var i = 0; i < numberOfSnowflakes; i++) {

      // clone our original snowflake and add it to snowflakeContainer
        var snowflakeCopy = originalSnowflake.cloneNode(true);
        snowflakeContainer.appendChild(snowflakeCopy);

    // set our snowflake's initial position and related properties
        var initialXPos = getPosition(50, browserWidth);
        var initialYPos = getPosition(50, browserHeight);
        var speed = 5+Math.random()*40;
        var radius = 4+Math.random()*10;

        // create our Snowflake object
        var snowflakeObject = new Snowflake(snowflakeCopy, 
                          radius, 
                          speed, 
                          initialXPos, 
                          initialYPos);
        snowflakes.push(snowflakeObject);
    }

    // remove the original snowflake because we no longer need it visible
  snowflakeContainer.removeChild(originalSnowflake);

  // call the moveSnowflakes function every 30 milliseconds
    moveSnowflakes();
}

//
// Responsible for moving each snowflake by calling its update function
//
function moveSnowflakes() {
    for (var i = 0; i < snowflakes.length; i++) {
        var snowflake = snowflakes[i];
        snowflake.update();
    }

  // Reset the position of all the snowflakes to a new value
    if (resetPosition) {
      browserWidth = document.documentElement.clientWidth;
      browserHeight = document.documentElement.clientHeight; 

    for (var i = 0; i < snowflakes.length; i++) {
          var snowflake = snowflakes[i];

          snowflake.xPos = getPosition(50, browserWidth);
          snowflake.yPos = getPosition(50, browserHeight);
      }

      resetPosition = false;
    }

    requestAnimationFrame(moveSnowflakes);
}

//
// This function returns a number between (maximum - offset) and (maximum + offset)
//
function getPosition(offset, size) {
  return Math.round(-1*offset + Math.random() * (size+2*offset));
}

//
// Trigger a reset of all the snowflakes' positions
//
function setResetFlag(e) {
  resetPosition = true;
}

预先感谢您的帮助!

非常感谢

最佳答案

生成雪花时, try catch 第 10 个雪花并应用您想要的内容

...

function generateSnowflakes() {
...
    // create each individual snowflake
    for (var i = 0; i < numberOfSnowflakes; i++) {

      // clone our original snowflake and add it to snowflakeContainer
        var snowflakeCopy = originalSnowflake.cloneNode(true);
        snowflakeContainer.appendChild(snowflakeCopy);

        // <------------------------------------------>
        // catch the tenth snowflake and add your changes here
        if (i === 9) {
          snowflakeCopy.classList.add("clickable");
          snowflakeCopy.addEventListener("click",function (e) {
            //the stuff you want to do
            //when the 10th snowflake is clicked
            // for example :
            window.location.replace("URL/OF/PRIZE");
          })
        }
....
}
...


```

关于javascript - 使用 JavaScript 在特定 div 上添加点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58938855/

相关文章:

javascript - jquery 如何在单击页面上的某个位置时隐藏侧边栏并删除类

javascript - 尝试用jQuery让div随机出现,效果不理想

jquery - 在初始化 jQuery 图像 slider 时显示加载器

javascript - jQuery clone() 复制数据……有时……?

javascript - 使用 JavaScript 将 Css 动画应用到带有 onclick 的类

javascript - jQuery LightSlider 不工作,但在 JSFiddle 中工作得很好

php - 插入新元素后更新 Yii 下拉列表

javascript - 如何使用 jQuery 应用嵌套的 css?

html - Opera/Safari 以不寻常的像素化方式显示我的自定义字体 (Fontface)。

html - 为什么我的左 div 对齐到底部?