blog專案 - 點擊圖片縮放
2020-09-20 23:22 995

新增了一個圖片縮放的功能
https://github.com/fat/zoom.js
它是一個很簡單的插件,所有擁有attribute data-action="zoom"的img元素都具有放大功能

<img src="img/blog_post_featured.png" data-action="zoom">

問題是,我在CKEditor中編輯的文章,雖然可以插入圖片,但沒有增加attribute的功能

screenshot of editing blog

因此須要找方法為所有img增加attribute,這裡就要用到jQuery
jQuery是一個可以簡單進行DOM操作的插件
比如說選取所有img執行某個js function

首先在header中引用jquery.js,不然根本不能用

<script src="~/lib/jquery/dist/jquery.js"></script>

之後blogBody的尾段插入jquery

<script>
        /* this part is to add attribute for zoom.js working. */
        $(".blogContent img").each(function () {
            $(this).attr("data-action", "zoom");
        });
</script>

將blogContent這個class內的所有img,每一個都執行一段,this增加attribute("data-action","zoom")

之後等網站blogBody加載完,就可以看到jquery執行,為img加上新的屬性。
zoom.js就會讀取這個屬性,為圖片加上縮放功能。
很好用對不對?