sortable實現拖拽功能
阿新 • • 發佈:2018-11-11
使用sortable這個強力外掛就很容易實現拖拽功能,它是目前比較牛逼的拖拽外掛,無需jquery,就可以全面支援pc和移動,參考以下github文件就有很詳細的說明,也給了很多
demo,外掛就用我給你的那個就可以,不用額外新增其他庫
GitHub:https://github.com/RubaXa/Sortable
以下的simple demo是我自己寫的,就這麼幾行簡單程式碼就完事了
simple demo:
html code:
<input type="hidden" value="" name="template_ending_order" id="template_ending_order">
<ul class="list-group" id="sort-ending-list">
<li class="list-group-item" draggable="false">致謝</li>
<li class="list-group-item" draggable="false">結論</li>
<li class="list-group-item">參考文獻</li>
</ul>
<submit id="form-save">儲存</submit)
js code:
$(document).ready( function(){
var ulElement = document.getElementById('sort-ending-list');
if (ulElement != null) {
var sortable = Sortable.create(ulElement, {
ghostClass: "sort-ghost"
});
}
$("#form-save").submit(function() {
setEndingOrder("#template_ending_order")
});
});
通過這個函式,將你的拖動結果拼接成一個字串,比如: "結論;參考文獻;致謝",你這個地方可以選擇id作為拼接結果,比如“1;2;3”
function setEndingOrder(endingOrderId){
var ulElement = document.getElementById('sort-ending-list');
var liElements = ulElement.children;
var value = "";
for (var i=0; i<liElements.length; ++i) {
if (i < liElements.length -1)
value += liElements[i].innerHTML + ';';
else
value += liElements[i].innerHTML;
}
var inputElement = document.getElementById(endingOrderId);
inputElement.value = value;
}
class Template < ActiveRecord::Base
ENDING_PARTS =
[
Setting.templates.ending_order_conclusion,
Setting.templates.ending_order_reference,
Setting.templates.ending_order_resume
]
validates :chapter_count, :presence => true, :inclusion => { :in => 1..9 }
validates :conclusion, :presence => true, :inclusion => { :in => [0,1] }
validates :achievement, :presence => true, :inclusion => { :in => [0,1] }
validates :introduction, :presence => true, :inclusion => { :in => [0,1] }
# Conditional Validation not Working
validates :ending_order, :presence => true, :if => :valid_ending_order?
def valid_ending_order?
cur_parts = self.ending_order.split(';')
cur_parts.each do |part|
if ENDING_PARTS.include?(part) == false
return false;
end
end
return true;
end
end
def update
@thesis = Thesis.find(params[:thesis_id])
@template = @thesis.templateif @template.update(template_params)
。。。。。。
else
render :edit
end
else
render :edit
end
end
private
def template_params
params.require(:template).permit(: :resume, :ending_order, :introduction)
end
def structure_params
params.require(:template).permit(:structure_id)
end