如何多次重用相同的代码 - html/css

2024-02-25

我想为每个按钮重复使用模式两次。

按钮代码:

function popUp_model(){
    const pop_up_model = document.getElementById('model');
 pop_up_model.classList.toggle('active');
}
body{
background: black;
}

.wrapper { display: flex; }

#container {
      display: flex;
      align-items: center;
      justify-content: center;
      margin: 0 100px;
    }
    .button {
      margin-top: 58px;
      align-content: left;
      --y: -25;
      --x: 0;
      --rotation: 0;
      --speed: 2;
      /* REMOVED: --txt: "About Me"; */
      --padding: 1rem 1.25rem;
      cursor: pointer;
      padding: var(--padding);
      border: 4px solid;
      border-color: #00fffe;
      color: white; /* changed */
      font-weight: bold;
      font-size: 1.25rem;
      transition: background 0.1s ease;
      background: hsl(var(--grey), 100%, 50%);
              animation-name: flow-and-shake;
      -webkit-animation-duration: calc(var(--speed) * 1s);
              animation-duration: calc(var(--speed) * 1s);
      -webkit-animation-iteration-count: infinite;
              animation-iteration-count: infinite;
      -webkit-animation-timing-function: ease-in-out;
              animation-timing-function: ease-in-out;
    }
   
    .button:hover {
      background: hsl(var(--grey), 100%, 40%);
      --speed: 0.1;
      --rotation: -1;
      --y: -1;
      --x: 1;
    }

    @-webkit-keyframes flow-and-shake {
      0%, 100% {
        transform: translate(calc(var(--x) * -1%), 0) rotate(calc(var(--rotation) * -1deg));
      }
      50% {
        transform: translate(calc(var(--x) * 1%), calc(var(--y) * 1%)) rotate(calc(var(--rotation) * 1deg));
      }
    }
    
    
    
    
/* modal*/
*,
*::after,
*::before {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
body1 {
  background: transparent;
  font-family: "Courier New", Courier, monospace;
  font-size: 18px;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}

.button {
  position: relative;
}

#model {
  position: absolute;
        z-index: 1;
  top: 50%;
  left: -100%;
  transform: translate(-50%, -50%);
  background: #101010;
  max-width: 450px;
  padding: 70px 50px;
  transition: 1s;
  visibility: hidden;
}
#model.active {
  visibility: visible;
  left: 50%;
}
#model .model-content {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}
#model .model-content img {
  width: 80px;
}
#model .model-content h2 {
  font-size: 24px;
  font-weight: 800;
  margin: 20px 0px;
}
.model-input {
  margin-top: 20px;
  width: 100%;
}
.model-input input {
  width: 100%;
  border: 1px solid;
  padding: 15px;
  outline: none;
  font-size: 18px;
}
.model-input input[type="submit"] {
  letter-spacing: 2px;
  cursor: pointer;
}
.model-input input[type="submit"]:hover {
  letter-spacing: 4px;
}
.close-model {
  position: absolute;
  top: 30px;
  right: 30px;
  cursor: pointer;
}
.close-model img {
  width: 20px;
}
<div id="container">
<div class="button__wrap">
  <button class="button" style="--hue: 162.03381670949574" onclick="popUp_model()" >About me</button>
  </div>
<div class="button__wrap">
  <button class="button" style="--hue: 162.03381670949574" onclick="popUp_model()">My Projects</button>
  <div class="button__shadow"></div>
</div>
</div>

对于上述每个按钮,我希望模态出现在单击时。

我想要模态两次。一个为About Me按钮,然后一个用于Projects按钮。这About Me按钮模式应该与Projects按钮一,因为我应该能够为每个模式添加不同的文本。关于如何重复使用模态代码两次有什么建议吗?


使用循环来迭代你的开放模式按钮元素。使用类来选择它们,然后在事件侦听器中迭代每一个。这可以使用querySelectorAll()选择打开模式的元素的方法(你的按钮) and a forEach循环遍历按钮元素。使用value and key在你的forEach循环处理与按钮配对的模态元素modal[key].

button.forEach((btn, i)=>{ 
   btn.addEventListener(()=>{
      modal[i].style.display = 'block';
      // the rest of the modal open code would go here 
   }) 
}).

这将使用key value i用于由事件侦听器触发的元素的迭代。根据您的模态代码设置方式,代码会有所不同...无论您是创建元素还是使用 CSS 使其可见...

下面是使用模态类型的对象及其内容来创建元素的代码示例。不过,您问题的关键是如何在每个函数上使用函数...嵌入事件侦听器的 forEach 循环可以解决问题modalBtn.forEach((el, i) => openModal(el, i));。在 openModal 函数中有一个事件监听器,它接受循环的参数value and key.

const modals = {
  0: {
    type: 'text',
    buttonName: 'First Modal',
    header: "Header for the First Modal",
    footer: "Footer for the first modal",
    content: 'Lorem ipsum dolor sit amet consectetur adipisicing elit. Est tempora, tenetur temporibus voluptatem quaerat facere sapiente quod aliquid veniam culpa itaque eius quibusdam vitae beatae magnam repellendus laborum molestias a.'
  },
  1: {
    type: 'image',
    buttonName: '1st Image',
    header: false,
    footer: 'This is a brief explaination of the image.',
    content: 'http://3.imimg.com/data3/VL/AV/MY-1921873/noida-authority-building-noida-uttar-pradesh-india-500x500.jpg'
  },
  2: {
    type: 'image',
    buttonName: '2nd Image',
    header: false,
    footer: 'This is another brief explaination of the image.',
    content: 'http://3.bp.blogspot.com/-I6NbACJixe4/TcQiPSDyXMI/AAAAAAAAAAo/7rFILVJI5sI/s1600/paisagens-naturais-brasil-2.jpg'
  },
  3: {
    type: 'text',
    buttonName: 'Fourth Modal',
    header: "This is the fourth Modal",
    footer: "This is the footer for the fourth modal",
    content: 'Lorem ipsum dolor sit amet consectetur adipisicing elit. Est tempora, tenetur temporibus voluptatem quaerat facere sapiente quod aliquid veniam culpa itaque eius quibusdam vitae beatae magnam repellendus laborum molestias a.'
  },
}

let cont = document.getElementById('modals');
let buttons = document.getElementById('buttons');
let images = document.getElementById('images');

// function to construct a text modal
function constTextModal(mod) {
  let button = document.createElement("BUTTON");
  let createModal = document.createElement("DIV");
  let createModalContent = document.createElement("DIV");
  let createModalHeader = document.createElement("DIV");
  let createCloseBtn = document.createElement("SPAN");
  let h2 = document.createElement("H2");
  let createModalBody = document.createElement("DIV");
  let modalPar = document.createElement("P");
  let createModalFooter = document.createElement("DIV");
  let h3 = document.createElement("H3");
  button.classList.add('textBtn');
  button.classList.add('modalBtn');
  button.textContent = `Open ${modals[mod].buttonName}`;
  createModal.classList.add('modal');
  createModalContent.classList.add('modal-content');
  createModalHeader.classList.add('modal-header');
  createCloseBtn.classList.add('closeBtn');
  createModalBody.classList.add('modal-body');
  createModalFooter.classList.add('modal-footer');
  buttons.append(button);
  cont.append(createModal);
  createModal.append(createModalContent);
  createModalContent.append(createModalHeader, createModalBody, createModalFooter);
  createModalHeader.append(createCloseBtn, h2);
  createModalBody.append(modalPar);
  createModalFooter.append(h3);
  createCloseBtn.textContent = 'x';
  h2.textContent = modals[mod].header;
  modalPar.textContent = modals[mod].content;
  createModalFooter.textContent = modals[mod].footer;
}

// function to contruct an image modal
function constImageModal(mod) {
  let button = document.createElement("BUTTON");
  let createModal = document.createElement("DIV");
  let createModalContent = document.createElement("DIV");
  let createCloseBtn = document.createElement("SPAN");
  let createModalHeader = document.createElement("DIV");
  let createModalBody = document.createElement("DIV");
  let modalImg = document.createElement("IMG");
  let createModalFooter = document.createElement("DIV");
  let h3 = document.createElement("H3");
  button.classList.add('textBtn');
  button.classList.add('modalBtn');
  button.textContent = `Open ${modals[mod].buttonName}`;
  createModalHeader.classList.add('img-header');
  createModal.classList.add('modal');
  createModalContent.classList.add('modal-content');
  createCloseBtn.className = 'closeBtn imgCloseBtn';
  createModalBody.classList.add('modal-body');
  modalImg.classList.add('modalImg');
  createModalFooter.classList.add('modal-footer');
  buttons.append(button);
  cont.append(createModal);
  createModal.append(createModalContent);
  createModalHeader.append(createCloseBtn);
  createModalContent.append(createModalHeader, createModalBody, createModalFooter);
  createModalBody.style.cssText = 'display: flex; justify-content: center; align-items: center;';
  createModalBody.append(modalImg);
  createModalFooter.append(h3);
  createCloseBtn.textContent = 'x';
  modalImg.src = modals[mod].content;
  createModalFooter.textContent = modals[mod].footer;
}

// conditional to check obj type
for (let mod in modals) {
  if (modals[mod].type === 'text') {
    constTextModal(mod);
  } else if (modals[mod].type === 'image') {
    constImageModal(mod);
  } else {
    // different type oif medium
  }
}

// get the modal element
let modal = document.querySelectorAll('.modal');

// get the modal button
let modalBtn = document.querySelectorAll('.modalBtn');

// get the close button
let closeBtn = document.querySelectorAll('.closeBtn');

// event listener to open the modal
modalBtn.forEach((el, i) => openModal(el, i));

// function to open the targeted modal
function openModal(el, i) {
  el.addEventListener('click', () => {
    modal[i].style.animationName = 'animateModal';
    modal[i].style.display = 'flex';
  })
}

// event listener to close the modal on closeBtn
closeBtn.forEach((el, i) => closeButton(el, i));

// function to close the targeted modal
function closeButton(el, i) {
  el.addEventListener('click', () => {
    modal[i].style.animationName = 'closeModal';
    setTimeout(() => {
      modal[i].style.display = 'none';
    }, 500);
  })
}

// event listener to close the modal on window click
window.addEventListener('click', clickOutside);

// funciton to close the targeted modal on outside click
function clickOutside(e) {
  modal.forEach((el, i) => {
    if (e.target == el) {
      modal[i].style.animationName = 'closeModal';
      setTimeout(() => {
        modal[i].style.display = 'none';
      }, 500);
    }
  })
}
body{
    font-family: Arial, Helvetica, sans-serif;
    font-size: 17px;
    line-height: 1.6;
}

.modalBtn {
    background: coral;
    padding: 1em 2em;
    color: #fff;
    border: 0;    
}

.imgCloseBtn {
    padding-right: 20px;
}

.modalBtn:hover{
    background-color: #333;
}

.modal {
    display: none;
    align-items: stretch;
    position: fixed;
    z-index: 1;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    overflow: auto;
    background-color: rgba(0,0,0,0.5);
    animation-name: animateModal;
    animation-duration: 0.7s;
    animation-timing-function: ease-in-out;
}

.modal-content {
    background: #f4f4f4;
    display: flex;
    align-items: stretch;
    flex-direction: column;
    margin: 20% auto;
    max-width: 70%;
    box-shadow: 0 5px 8px 0 rgba(0,0,0,0.2),  0 7px 20px 0 rgba(0,0,0,0.2);
    animation-name: animateModal;
    animation-duration: 0.7s;
    animation-timing-function: ease-in-out;
    border-radius: 21px;
}

.modal-header h2, .modal-footer h3 {
    margin: 0;
}

.modal-header {
    background: coral;
    padding: 15px;
    color: #f4f4f4;
    border-top-left-radius: 20px;
    border-top-right-radius: 20px;
}

.modal-body {
    padding: 10px 20px;
    background-color: #fff;
}

.modal-footer {
    background: coral;
    padding: 10px;
    color: #fff;
    text-align: center;
    border-bottom-left-radius: 20px;
    border-bottom-right-radius: 20px;
}

.closeBtn {
    color: #ccc;
    font-size: 20px;
    float: right; 
}

.closeBtn:hover, .closeBtn:focus {
    color: #000;
    text-decoration: none;
    cursor: pointer;
}

@keyframes animateModal {
    from {
        opacity: 0;
    }
    to {
        opacity: 1;
    }
}

@keyframes closeModal {
    from {
        opacity: 1;
    }
    to {
        opacity: 0;
    }
}
<div id="buttons">
</div>

<div id="images">
</div>

<div id="modals">
</div>

注意:一旦我在我的constModal上面的函数,然后我可以使用以下方法向它们添加一个类,button.classList.add('modalBtn');,所以我的按钮元素将具有该类modalBtn。因此,当我迭代该类时,我可以使用以下方式调用模态类选择器let modal = document.querySelectorAll('.modal');并在 a 中创建一个事件侦听器forEach使用按钮索引的循环,在forEach循环,获取我希望打开的模态元素,使用它相应的索引 =>modal[i].

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何多次重用相同的代码 - html/css 的相关文章

  • jquery 中的函数返回未定义[重复]

    这个问题在这里已经有答案了 我在 jquery 中调用的函数返回未定义 我检查了该函数 当我对其进行调试时 它返回正确的数据 function addToPlaylist component type add to pl value pl
  • 全高全宽 CSS 布局

    我正在寻找一种方法来创建具有 5 个区域的纯 CSS 无 JavaScript 布局 如下所示 H A B C F
  • iphone jquery 移动闪烁问题

    我在 iPhone 上使用使用 jQuery mobile 开发的应用程序时遇到闪烁问题 我尝试了互联网上提供的几种解决方案 包括 CSS 更改 将过渡设置为 无 甚至在 jquerymobile js 中注释代码 但没有运气 我使用的 J
  • Chrome --app 相当于 Firefox\IE

    我有一个网络应用程序 客户要求单击不同按钮时更改浏览器窗口大小 我发现在那link https stackoverflow com questions 13436855 launch google chrome from the comma
  • Angular2:动态同步http请求

    Goal 发出一系列同步 http 请求并能够将它们作为一个可观察流进行订阅 示例 不工作 let query arr test1 test2 test3 function make request query arr if query a
  • HTML5 文件 API 和 AJAX 上传分块问题

    我编写了一个带有单独进度的拖放多个文件上传等 除了一件事之外 它工作得非常好 上传较大文件时 有时浏览器会锁定 直到上传完成 我认为这是因为该文件存储在浏览器的内存中并占用了浏览器可用的所有资源 我想知道 是否可以逐段读取文件并在读取时通过
  • Angular JS - 使服务可以从控制器和视图全局访问

    假设我们有以下服务 myApp factory FooService function 然后 从控制器中 我会说 myApp controller FooCtrl scope FooService function scope FooSer
  • 为什么 call 比 apply 快那么多?

    我想知道是否有人知道why call比apply 在 Chrome 中 速度大约快 4 倍 在 Firefox 中快 30 倍 我什至可以制作自定义原型 apply2 在大多数情况下 运行速度是apply 这个想法取自角度 Function
  • 从网页运行 ClickOnce 应用程序,无需用户操作

    我们有一个基于 Java 的 Web 应用程序以及用 C 编写的相同应用程序 如果 java 检查器发现客户端计算机上没有安装 Java 则应该运行该应用程序 这个想法是运行 C 单击一次 http en wikipedia org wik
  • 了解 Document.createElement()

    我在用着GWT及其底层DOM能力 我基本上想要实现的是 Have a div包含一些文本的元素 其中一些文本将被包围span元素 span 元素可相互拖动并提供上下文菜单 New span元素可以由最终用户动态创建 它可能是这样的 在应用程
  • 如何将MathJax公式转换为img

    Mathjax 现在在我的项目中运行良好 但有一个问题 有没有办法将MathJax的公式 纯html和css 转换成img文件 我可以保存 MathJax 可以配置为生成 SVG 看http docs mathjax org en late
  • 如何解决“消息端口在收到响应之前已关闭”的问题。在 JavaScript 中的 window.location.reload() 之后

    我遇到了 javascript 问题 从 chrome v73 0 3683 86 开始 每当我在 window location reload 函数之后运行 javascript 代码时 它总是给我错误 Unchecked runtime
  • 如何在 React Native 中使用相同的 Firebase 数据库在两个应用程序之间进行通信?

    我有两个不同的应用程序使用相同的实时数据库 在第一个应用程序中 我发送的订单包含一些要保存在数据库中的数据字段 在另一个应用程序中 我只添加一个侦听器 firebase database ref userOrder currentUser
  • 如何在 TypeScript 中使用 navigation.replace ?

    我试图在我的代码中使用它 const navigation useNavigation navigation replace AllFriends 但我不断收到错误消息 Property replace does not exist on
  • 选择子元素但不选择孙元素

    我有以下简化的代码 div p text p div div p text p div div p text p div div p text p div 每当我设置一些值时 content pCSS 文件中的元素 更改也适用于 col1
  • Flexbox 项目的完美圆形边框半径[重复]

    这个问题在这里已经有答案了 我有类似这样的项目 它们是弹性盒容器内的弹性项目 我的正常尺寸物品 我的物品被挤压 我的 CSS 看起来像这样 body display flex flex direction column align item
  • 从更多元素中仅获取唯一名称

    我动态渲染了 HTML 其中列出了未确定数量的单选按钮 这些按钮的名称代表数据库中的某些 id 我需要收集收音机的所有唯一名称 这是一个例子
  • 将网站加载到 DIV 中

    当我在文本框中写入 URL 然后单击提交按钮时 如何实际从网站检索数据 我希望将数据放入我拥有的 div 中 这可能吗 我已经尝试过这个 但它不起作用
  • 如何从 html 字符串向 jQuery DataTable 添加多行

    我有一个 jQuery DataTable 我想向其中添加 html tr 行 这些行以 html 字符串的形式出现 我可以使用标准 jQuery 将它们添加到表中 但这意味着它们绕过 DataTable 对象 并在重新排序表时丢失 要使用
  • Cycle2 初始化事件未触发

    我使用 Cycle2 作为基本的轮播 我的幻灯片项目有时在其数据中包含一个 url 因此我必须使用 Cycle2 api 事件来使用该 url 当它存在时 我的问题是 虽然 cycle after 事件触发正常 但初始化事件都不会触发 因此

随机推荐

  • 适用于 Windows 的便携式 Ruby on Rails 环境

    有人问了同样的问题 https stackoverflow com questions 258801 portable ruby on rails environment大约两年前 当时的答案是InstantRails 但 InstantR
  • 如何在 Objective-C 中测试相等性?

    比较顶视图时 第一个 无法执行 相等测试失败 In init i self setCurrentPuzzleView p1 后来 我 if self currentPuzzleView p1 NSLog Removing P1 from S
  • Google Cloud ML Engine 错误 429 内存不足

    我将模型上传到 ML engine 当尝试进行预测时 我收到以下错误 ERROR gcloud ml engine predict HTTP request failed Response error code 429 message Pr
  • 将数组的内容打印为字符串

    我正在尝试编写一个小函数 它接受整数数据并将其转换为 char 数组内的十六进制值 我想做的是 取int数组数据 将其转换为另一个数组中的十六进制 将十六进制数组的内容转换为字符串 打印字符串的内容 int main int data 40
  • phpmailer如何向两个不同的用户发送两条不同的消息

    我正在向两个不同的人发送邮件 两封不同的消息 一封发送给用户 一封发送给管理员 message1 hello user message2 hello admin email email protected cdn cgi l email p
  • Clojure 测试框架的优势?

    您更喜欢哪一个 为什么 各自的优点和缺点是什么 在什么情况下 每个人都比其他人更胜一筹 我对 midje 与 clojure test 特别感兴趣 但也可以随意提出其他 Clojure 测试框架 也可以看看Clojure 的最佳单元测试框架
  • 在静态方法中在 UIView 上用清晰的颜色绘制(切一个洞)

    我有一个iPhone应用程序 我需要实现以下方法 UITextView textView UITextView withCuttedRect CGRect r 此方法必须剪切 填充 UIColor clearColor 矩形r from U
  • 在同一套接字上并行调用 send/recv 是否有效?

    我们可以在同一个套接字上从一个线程调用 send 并从另一个线程调用 receive 吗 我们可以从同一套接字上的不同线程并行调用多个发送吗 我知道好的设计应该避免这种情况 但我不清楚这些系统 API 的行为方式 我也找不到同样的好的文档
  • 表单不提交动态生成的输入(jQuery)

    您好 我正在尝试为我的表单动态生成一些输入 但它没有发布生成的新输入 到目前为止我一直在四处搜索 我唯一能找到的就是使表单成为body 标签 并且在我的应用程序的设计中这是不可能的 所以有人可能知道会发生什么以及如何解决它 不 它不适用于
  • 如何在 Visual Studio Code 中显示 Jupyter Notebook 中的所有输出?

    在 VS Code 中的 Jupyter Notebook 中 当我运行在某个时刻打印大量输出的代码时 剩余的输出将被抑制并显示一条消息 显示更多 在文本编辑器中打开原始输出数据 如何使所有输出可见 我认为你在这里使用内部构建是正确的设置
  • Flink:处理数据早于应用程序水印的键控流

    我正在使用带有运动源和事件时间键控窗口的 F link 该应用程序将监听实时数据流 窗口 事件时间窗口 并处理每个键控流 我有另一个用例 我还需要能够支持某些关键流的旧数据的回填 这些将是事件时间 鉴于我正在使用水印 这会成为一个问题 因为
  • Azure Functions - Blob 流动态输入绑定

    我正在 azure 上运行一个 C 函数 它需要从容器中获取文件 唯一的问题是输入文件的路径每次都会 可能 不同 并且输入文件的数量将从 1 到大约 4 或 5 不等 因此 我不能只使用默认的输入 blob 绑定据我所知 我的选择是给予容器
  • 通过Ajax发送FormData + js变量

    我有这个 Ajax 来发送多个图像 btn on click function var formData new FormData form1 0 var path php upload adm prodpictures php ajax
  • 如何转到 Eclipse 中的“下一个出现”

    在 Eclipse 中 您可以打开 标记出现次数 然后它将突出显示当前范围内给定变量的每次出现 那太好了 但我真的很想从一次这样的事件转移到下一次 到目前为止 我已经找到了两个关于如何执行此操作的建议 但都没有奏效 首先有这样的帖子 Ecl
  • 使用 configparser 添加注释

    我可以使用 python 中的 ConfigParser 模块使用 add section 和 set 方法创建 ini 文件 请参阅示例http docs python org library configparser html http
  • 调试 $rootScope:infdig

    这是一个常见问题 已达到 5 次 digest 迭代 流产 观察者在最近 5 次迭代中被解雇 文档 https docs angularjs org error https docs angularjs org error rootScop
  • 自动更新 HTML 画布宽度和高度属性

    我想将 HTML5 画布与 Flexbox 结合使用 当用户调整窗口大小时 我需要自动设置 canvas width 和 canvas height 我尝试使用 jQuery 来实现 cnvs attr width cnvs width c
  • “Google_Exception”,消息为“经过身份验证后无法添加服务”

    我正在使用 Oauth 2 0 开发带有 Google Analytics 的 WP 插件 我所有的身份验证和数据提取都工作正常 除了这个问题 第一次获得新的 Google 授权代码 例如 4 xbSbg 并进行身份验证 然后尝试调用new
  • 我可以在 AngularJS 中要求通用父指令吗

    子指令是否可以在不确切知道父指令是什么的情况下需要父指令 而只是知道它 实现了一个接口 例如
  • 如何多次重用相同的代码 - html/css

    我想为每个按钮重复使用模式两次 按钮代码 function popUp model const pop up model document getElementById model pop up model classList toggle