jQuery實現照片牆,附步驟詳解


現在一直使用vue寫項目,發現之前的js都很生疏了,寫個小demo練下手,看一下最終效果展示
功能點:點擊添加圖片隨機添加一張圖片,圖片可以拖動,可以點擊刪除
技能點: 主要使用了jQuery的一些方法
下面就一步一步來實現它吧
一開始我想做一個按鈕可以讓用戶自己上傳圖片,結果寫了之后發現沒有圖片上傳的服務接口,也懶得去找了,就直接使用本地的圖片了,這里也把圖片上傳的功能寫一下,如果你有圖片上傳的api可以直接使用
 
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <link rel="stylesheet" href="./sass/index.css">
  <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
</head>

<body>
  <div class="meaasge_contanier">
    <ul class="picture_list">
      <div class="upload">
        <div class="plus">添加照片</div>
        <input id="filebtn" type="file" accept="image/gif, image/jpeg">
      </div>
    </ul>
  </div>
</body>
<script type="text/javascript">
  $(function () {
    // 如果有后台圖片接口,可以使用文件上傳
    $('.plus').on('click', function (e) {
      // 點擊添加照片,觸發input上傳事件
      if ($('#filebtn')) {
        $('#filebtn').click()
      }
      e.preventDefault()
    })
    $('#filebtn').change(function () {
      // input內容改變時,拿到文件,傳給后台獲取線上圖片地址
      const file = $('#filebtn')[0].files
      console.log(777, file)
      $.ajax({
        url: '',
        .....
      })
    })
  })
</script>
</html>

 

這里我用的是本地的圖片,寫了一個img.js,在里面放了一些圖片,圖片地址都是百度找的
img.js
  var list = [
    {
      "id": 0,
      "name": "1",
      "date": "2017-5-26",
      "url": "http://img4.imgtn.bdimg.com/it/u=1433191751,1566568157&fm=26&gp=0.jpg"
    },
    ...
  ]
 
接着寫一個點擊事件,點擊添加照片的按鈕網頁面上加一張圖片
html的寫法不變,把input標簽去掉,這里不需要用戶上傳

script寫法
先把圖片文件引入,這樣可以拿到圖片地址數組
<script src="./img.js"></script>
<script type="text/javascript">
  $(function () {
    // 添加圖片
    $('.plus').click(function () {
      const liList = $('.picture_list .item')
      // 限制圖片不能多於30張
      if (liList && liList.length > 30) {
        window.alert('圖片太多啦,先刪掉一些圖片')
        return
      }

      // 設置初始的top和left值
      let liTop = 150
      let liLeft = 100
      if (liList && liList.length) {
        // 獲取最后一個li的位置
        let lastLi = $('.picture_list li:last-child')
        let t = Number(lastLi.css('top').replace('px', ''))
        let l = Number(lastLi.css('left').replace('px', ''))

        // 圖片心型排列方法
        let length = liList.length
        if (length < 9) { // 右下走向
          liTop = t + 30
          liLeft = l + 30
        } else if (length > 8 && length < 17) { // 右上走向
          liTop = t - 30
          liLeft = l + 30
        } else if (length > 16 && length < 23) { // 左下走向
          if (length === 17) {
            liLeft = l - 60
          } else liLeft = l - 30
          liTop = t + 30
        } else if (length > 22) { // 左上走向
          liTop = t - 30
          liLeft = l - 30
        }
      }
      // console.log(index, liList)
      // 生成一個圖片
      // 准備了7張圖片,這里生成0-6的隨機數,用於取圖
      let index = Math.round(Math.random() * 10)
      if (index > 6) {
        index = Math.round(index * 0.6)
      }
      const url = list[index].url
      // 添加到ul中
      if (!liList || liList.length < 31) {
        const li = $(`<li class="item"><div class="delete">x</div><img src="${url}" /></li>`).css({
          'top': liTop,
          'left': liLeft
        })
        $('.picture_list').append(li)
      }
    })
  })
</script>
看一下效果:
 
現在加上圖片的移動和刪除看看,加了圖片的移動后,圖片的位置就發生改動,使用上面的排列方式就沒有意義.添加圖片時我就直接在最后一張圖片后偏移一點.這里需要限制一下圖片的top和left的最大最小值,以免超出牆壁范圍
 
<script type="text/javascript">
  $(function () {
    // 添加圖片
    $('.plus').click(function () {
      const liList = $('.picture_list .item')
      if (liList && liList.length > 30) {
        window.alert('圖片太多啦,先刪掉一些圖片')
        return
      }
      // 准備了7張圖片,這里生成0-6的隨機數,用於取圖
      let index = Math.round(Math.random() * 10)
      if (index > 6) {
        index = Math.round(index * 0.6)
      }
      // 設置初始的top和left值
      let liTop = 150
      let liLeft = 100
      if (liList && liList.length) {
        // 獲取最后一個li的位置
        let lastLi = $('.picture_list li:last-child')
        let t = Number(lastLi.css('top').replace('px', ''))
        let l = Number(lastLi.css('left').replace('px', ''))
        console.log(lastLi, t, l)
        // 圖片邊界判斷,讓生成的圖片位置在一定范圍
        l = l < 100 ? 100 : l
        l = l > contanier.width() - lastLi.width() - 100 ? 100 : l
        t = t < 100 ? 100 : t
        t = t > contanier.height() - lastLi.height() - 100 ? 100 : t
        // 每次圖片都在上一張的基礎上排列
        liTop = t + 30
        liLeft = l + 30
      }
      // console.log(index, liList)
      // 生成一個圖片
      const url = list[index].url
      if (!liList || liList.length < 31) {
        const li = $(`<li class="item"><div class="delete">x</div><img src="${url}" /></li>`).css({
          'top': liTop,
          'left': liLeft
        })
        $('.picture_list').append(li)
      }
    })

    // 圖片的盒子li標簽是動態生成的,在綁定事件時不能直接綁定在li標簽上,綁定在它的父元素上
    // 圖片移動
    let pictureList = $('.picture_list')
    let contanier = $('.meaasge_contanier')
    pictureList.on('mousedown', '.item', function (e) {
      e.preventDefault()
      // 讓點擊的圖片在第一層級
      let arr = Array.from($('.item'))
      arr.forEach(item => {
        $(item).css({
          zIndex: 0
        })
      })
      let item = $(this)
      $(item).css({
        zIndex: 99
      })
      // 獲取當前位置的clientX,和當前圖片的top值,left值,得到它們相減部分的值
      const disX = e.clientX - item[0].offsetLeft
      const disY = e.clientY - item[0].offsetTop

      contanier.mousemove(function (event) {
        event.preventDefault()
        // 用移動時的位置的clientX減去初始的差值,就得到現在的top值與left值
        let x = event.clientX - disX
        let y = event.clientY - disY
        x = x < 0 ? 0 : x
        x = x > contanier.width() - item.width() ? contanier.width() - item.width() : x
        y = y < 0 ? 0 : y
        y = y > contanier.height() - item.height() ? contanier.height() - item.height() : y
        item.css({
          top: y,
          left: x
        })
      })
      // 鼠標移出盒子停止圖片移動
      contanier.mouseout(function () {
        contanier.off('mousemove')
        contanier.off('mouseup')
      })
      // 鼠標彈起停止圖片移動
      contanier.mouseup(function () {
        contanier.off('mousemove')
        contanier.off('mouseup')
      })
    })

    // 圖片刪除
    // 圖片和刪除按鈕都是動態添加的,都需要用on綁定事件
    pictureList.on('click', '.delete', function () {
      // 刪除當前點擊的圖片
      $(this).parent('.item').remove()
    })
    // 鼠標移入,刪除按鈕展示
    pictureList.on('mouseover', '.item', function () {
      $(this).children('.delete').show()
    })
    // 鼠標移出,刪除按鈕隱藏
    pictureList.on('mouseout', '.item', function () {
      $(this).children('.delete').hide()
    })
  })
</script>

最終的效果:

 

css代碼

li {
  list-style: none;
}
.meaasge_contanier {
  width: 800px;
  height: 600px;
  margin: 100px auto 0;
  background-color: sienna; 
  position: relative;
  background: url('../img/board.jpg');
  border: 3px solid #a25124;
  border-radius: 10px;
  box-shadow: 3px 3px 5px #a25124;
}
.meaasge_contanier .upload {
  width: 120px;
  height: 40px;
  position: absolute;
  top: 5px;
  left: 5px;
  text-align: center;
}
.meaasge_contanier .upload .plus {
  width: 100%;
  height: 100%;
  text-align: center;
  line-height: 40px;
  position: absolute;
  background-color: #eee;
  cursor: pointer;
  border-radius: 5px;
}
.meaasge_contanier .upload input {
  width: 150px;
  overflow: hidden;
}
.meaasge_contanier .picture_list .item {
  width: 100px;
  position: absolute;
  box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.3);
}
.meaasge_contanier .picture_list .item img {
  width: 100%;
}
.meaasge_contanier .picture_list .item .delete {
  position: absolute;
  width: 20px;
  height: 20px;
  line-height: 17px;
  text-align: center;
  border-radius: 50%;
  background-color: #909399;
  color: #fff;
  font-size: 12px;
  top: -5px;
  right: -5px;
  display: none;
  cursor: default;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM