2017-08-10 81 views
0

我想用.wrap().unwrap()單擊此div時,添加border圍繞div但問題是,出現在頁面周圍沒有div。爲什麼頂部的邊界?圍繞一個div創建一個邊界與jQuery

這裏是我的代碼:

$("#add").click(function() { 
 
    //"main" is a tag. 
 
    $("main").append('<div class="cards"><div class="card new" style="width: 20rem;">\ 
 
     <div class="layer"></div>\ 
 
      <div class="card-block">\ 
 
       <h4 class="card-title"></h4>\ 
 
       <p class="card-text"></p>\ 
 
      </div>\ 
 
      <div class="card-block">\ 
 
       <div class="delete">Del</div>\ 
 
       <div class="edit" data-toggle="modal" data-target="#note">edit</div>\ 
 
      </div>\ 
 
     </div></div>'); 
 
    var title = $("#noteTitle").val(); 
 
    var text = $("#noteBody").val(); 
 
    $(".new h4").html(title); 
 
    $(".new p").html(text); 
 
    var layer = $("#selected").css("background-color"); 
 
    $(".new .layer").css({ 
 
    "background-color": layer, 
 
    "position": "absolute", 
 
    "opacity": ".2", 
 
    "top": "0", 
 
    "left": "0", 
 
    "width": "100%", 
 
    "height": "100%" 
 
    }); 
 
$(".card").removeClass("new"); 
 
}); 
 
$("main").on("click", ".card", function() { 
 
    if ($(this).parent().is(".border")) { 
 
    $(this).unwrap(); 
 
    } else { 
 
    $(this).wrap('<div class="border"></div>'); 
 
    } 
 

 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
 
<input type="text" id="noteTitle" /> 
 
<textarea id="noteBody" ></textarea> 
 
<button id="add">Click</button> 
 
<main></main>

CSS:

.card { 
margin: 10px; 
height:230px; 
background: url(paper.jpg); 
background-repeat: no-repeat; 
background-size: cover; 
display: inline-block; 
word-wrap: break-word; 
font-family: "comic sans MS"; 
float: left; 
padding-right: 60px; 
z-index:-1; 
} 
.border { 
border: solid 20px black; 
} 
+0

的console.log(本)......在上( '點擊',...)回調。它是主要元素還是卡類? – Argee

+0

你圍繞一個'.border'。讓我們看看'css',有沒有一個原因讓你不只是在'jQuery'中添加'.css'? –

+0

它看起來像是包裝和解開'

'標籤 –

回答

0

你可能會想切換你想要一個邊界DIV CSS類不要添加類「邊框」的新div。你正在做的是在頂部添加一個沒有內容的新的div,所以它不包圍。而你將要添加的CSS是使用類似border: 1px solid black

超級簡單的例子懸停的CSS ...只是修改代碼以jQuery中

http://jsbin.com/fibogojulo/edit?html,css,output

添加/刪除一個類上點擊的邊界片
0

有更簡單的方法來添加邊框比使用div的周圍...使用CSS屬性邊框,你可以很容易地做到這一點。

$('#button').click(function() { 
 
    $('#div').css('border', '1px solid black'); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 
 
<button id="button">Press me</button> 
 
<div id="div">hello</div>