根据宽度调整图像大小-CSS或Javascript

时间:2019-05-08 11:38:00

标签: javascript html css resize

问题:每当调整节的大小时,我都在努力构造行。

说明:如果使用拖动线将右侧部分的尺寸缩小,图片将变小。

当部分宽度小于500px时,如何编码每行只有一张图片(全行宽)?

请导航至以下链接以获取Codepen示例

Codepen link

如果有人建议或帮助我解决这个问题,我将非常感谢。

以下是我的代码:

HTML:

<article id="links">At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
</article>

<div id="schiebeteil"></div>

<article id="rechts">

    <section class="main-nav">
        <div id="myBtnContainer">
            <button class="btn active" onclick="filterSelection('all')">All works</button>
            <button class="btn" onclick="filterSelection('illustrations')">Illustrations</button>
            <button class="btn" onclick="filterSelection('animations')">Animations</button>
        </div>
    </section>

    <section class="image-content">

        <div class="column illustrations">
            <div class="content">
                <img src="https://www.uni-weimar.de/fileadmin/user/uni/hauptseiten/Startseite/Buehnenbanner/2019/04/csm_campusoffice_8e3bb1122c.jpg">
                <h4>Mountains</h4>
            </div>
        </div>

        <div class="column illustrations">
            <div class="content">
                <img src="https://www.uni-weimar.de/fileadmin/user/uni/hauptseiten/Startseite/Buehnenbanner/2019/04/csm_campusoffice_8e3bb1122c.jpg">
                <h4>Mountains</h4>
            </div>
        </div>

        <div class="column illustrations">
            <div class="content">
                <img src="https://www.uni-weimar.de/fileadmin/user/uni/hauptseiten/Startseite/Buehnenbanner/2019/04/csm_campusoffice_8e3bb1122c.jpg">
                <h4>Mountains</h4>
            </div>
        </div>

        <div class="column animations">
            <div class="content">
                <img src="https://www.uni-weimar.de/fileadmin/user/uni/hauptseiten/Startseite/Buehnenbanner/2019/04/csm_campusoffice_8e3bb1122c.jpg">
                <h4>Mountains</h4>
            </div>
        </div>

    </section>

</article>

CSS:

* {
    font-family: Arial;
    font-size: 40px;
    box-sizing: border-box;
    font-weight: normal;
}

body {
    height: 100%;
    display: flex;
    background-color: #eee;
}

#links,
#rechts {
    width: 100%;
    height: 100vh;
    flex: 1 1 auto;
    flex-direction: column;
    min-width: 20%;
    overflow-y: auto;
}

#schiebeteil {
    width: 3px;
    flex: 0 0 auto;
    cursor: col-resize;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: black;
}


/* Create three equal columns that floats next to each other */

.column {
    float: left;
    width: 50%;
    display: none;
    /* Hide all elements by default */
}


/* Content */

.content {
    padding: 10px;
}


/* The "show" class is added to the filtered elements */

.show {
    display: block;
}

#myBtnContainer {
    margin: 0 auto;
    height: 100%;
    margin: 0px;
    padding: 0px;
}


/* Style the buttons */

.btn {
    border: none;
    outline: none;
    cursor: pointer;
    background: none;
    color: black;
    padding: 0;
    margin: 0;
    line-height: 96%;
    font-size: 18px;
    margin-right: 20px;
    float: right;
    height: 100%;
}

.btn:hover {}

.btn.active {}

img {
    width: 100%;
}

h4 {
    font-size: 18px;
    padding: 0;
    margin: 0;
}

.image-content {
    float: left;
    margin-left: 48px;
}

.main-nav {
    width: 100vh;
    height: 45px;
    position: fixed;
    -webkit-transform-origin: left top;
    -webkit-transform: rotate(-90deg) translateX(-100%);
}

JavaScript :(标记内的引用)

filterSelection("all")

function filterSelection(c) {
    var x, i;
    x = document.getElementsByClassName("column");
    if (c == "all") c = "";
    for (i = 0; i < x.length; i++) {
        w3RemoveClass(x[i], "show");
        if (x[i].className.indexOf(c) > -1) w3AddClass(x[i], "show");
    }
}

function w3AddClass(element, name) {
    var i, arr1, arr2;
    arr1 = element.className.split(" ");
    arr2 = name.split(" ");
    for (i = 0; i < arr2.length; i++) {
        if (arr1.indexOf(arr2[i]) == -1) {
            element.className += " " + arr2[i];
        }
    }
}

function w3RemoveClass(element, name) {
    var i, arr1, arr2;
    arr1 = element.className.split(" ");
    arr2 = name.split(" ");
    for (i = 0; i < arr2.length; i++) {
        while (arr1.indexOf(arr2[i]) > -1) {
            arr1.splice(arr1.indexOf(arr2[i]), 1);
        }
    }
    element.className = arr1.join(" ");
}


// Add active class to the current button (highlight it)
var btnContainer = document.getElementById("myBtnContainer");
var btns = btnContainer.getElementsByClassName("btn");
for (var i = 0; i < btns.length; i++) {
    btns[i].addEventListener("click", function() {
        var current = document.getElementsByClassName("active");
        current[0].className = current[0].className.replace(" active", "");
        this.className += " active";
    });
}

Javascript-Resizable.js

/// <reference path="../bower_components/jquery/dist/jquery.js" />
/*
jquery-resizable
Version 0.32 - 5/5/2018
© 2015-2018 Rick Strahl, West Wind Technologies
www.west-wind.com
Licensed under MIT License
*/
(function(factory, undefined) {
    if (typeof define === "function" && define.amd) {
        // AMD
        define(["jquery"], factory);
    } else if (typeof module === "object" && typeof module.exports === "object") {
        // CommonJS
        module.exports = factory(require("jquery"));
    } else {
        // Global jQuery
        factory(jQuery);
    }
}(function($, undefined) {

    if ($.fn.resizable)
        return;

    $.fn.resizable = function fnResizable(options) {
        var defaultOptions = {
            // selector for handle that starts dragging
            handleSelector: null,
            // resize the width
            resizeWidth: true,
            // resize the height
            resizeHeight: true,
            // the side that the width resizing is relative to
            resizeWidthFrom: "right",
            // the side that the height resizing is relative to
            resizeHeightFrom: "bottom",
            // hook into start drag operation (event passed)
            onDragStart: null,
            // hook into stop drag operation (event passed)
            onDragEnd: null,
            // hook into each drag operation (event passed)
            onDrag: null,
            // disable touch-action on $handle
            // prevents browser level actions like forward back gestures
            touchActionNone: true,
            // instance id
            instanceId: null
        };
        if (typeof options == "object")
            defaultOptions = $.extend(defaultOptions, options);

        return this.each(function() {
            var opt = $.extend({}, defaultOptions);
            if (!opt.instanceId)
                opt.instanceId = "rsz_" + new Date().getTime();

            var startPos, startTransition;

            // get the element to resize 
            var $el = $(this);
            var $handle;

            if (options === "destroy") {
                opt = $el.data("resizable");
                if (!opt)
                    return;

                $handle = getHandle(opt.handleSelector, $el);
                $handle.off("mousedown." + opt.instanceId + " touchstart." + opt.instanceId);
                if (opt.touchActionNone)
                    $handle.css("touch-action", "");
                $el.removeClass("resizable");
                return;
            }

            $el.data("resizable", opt);

            // get the drag handle

            $handle = getHandle(opt.handleSelector, $el);

            if (opt.touchActionNone)
                $handle.css("touch-action", "none");

            $el.addClass("resizable");
            $handle.on("mousedown." + opt.instanceId + " touchstart." + opt.instanceId, startDragging);

            function noop(e) {
                e.stopPropagation();
                e.preventDefault();
            };

            function startDragging(e) {
                // Prevent dragging a ghost image in HTML5 / Firefox and maybe others    
                if (e.preventDefault) {
                    e.preventDefault();
                }

                startPos = getMousePos(e);
                startPos.width = parseInt($el.width(), 10);
                startPos.height = parseInt($el.height(), 10);

                startTransition = $el.css("transition");
                $el.css("transition", "none");

                if (opt.onDragStart) {
                    if (opt.onDragStart(e, $el, opt) === false)
                        return;
                }

                $(document).on("mousemove." + opt.instanceId, doDrag);
                $(document).on("mouseup." + opt.instanceId, stopDragging);
                if (window.Touch || navigator.maxTouchPoints) {
                    $(document).on("touchmove." + opt.instanceId, doDrag);
                    $(document).on("touchend." + opt.instanceId, stopDragging);
                }
                $(document).on("selectstart." + opt.instanceId, noop); // disable selection
                $("iframe").css("pointer-events", "none");
            }

            function doDrag(e) {

                var pos = getMousePos(e),
                    newWidth, newHeight;

                if (opt.resizeWidthFrom === "left")
                    newWidth = startPos.width - pos.x + startPos.x;
                else
                    newWidth = startPos.width + pos.x - startPos.x;

                if (opt.resizeHeightFrom === "top")
                    newHeight = startPos.height - pos.y + startPos.y;
                else
                    newHeight = startPos.height + pos.y - startPos.y;

                if (!opt.onDrag || opt.onDrag(e, $el, newWidth, newHeight, opt) !== false) {
                    if (opt.resizeHeight)
                        $el.height(newHeight);

                    if (opt.resizeWidth)
                        $el.width(newWidth);
                }
            }

            function stopDragging(e) {
                e.stopPropagation();
                e.preventDefault();

                $(document).off("mousemove." + opt.instanceId);
                $(document).off("mouseup." + opt.instanceId);

                if (window.Touch || navigator.maxTouchPoints) {
                    $(document).off("touchmove." + opt.instanceId);
                    $(document).off("touchend." + opt.instanceId);
                }
                $(document).off("selectstart." + opt.instanceId, noop);

                // reset changed values
                $el.css("transition", startTransition);
                $("iframe").css("pointer-events", "auto");

                if (opt.onDragEnd)
                    opt.onDragEnd(e, $el, opt);

                return false;
            }

            function getMousePos(e) {
                var pos = {
                    x: 0,
                    y: 0,
                    width: 0,
                    height: 0
                };
                if (typeof e.clientX === "number") {
                    pos.x = e.clientX;
                    pos.y = e.clientY;
                } else if (e.originalEvent.touches) {
                    pos.x = e.originalEvent.touches[0].clientX;
                    pos.y = e.originalEvent.touches[0].clientY;
                } else
                    return null;

                return pos;
            }

            function getHandle(selector, $el) {
                if (selector && selector.trim()[0] === ">") {
                    selector = selector.trim().replace(/^>\s*/, "");
                    return $el.find(selector);
                }

                // Search for the selector, but only in the parent element to limit the scope
                // This works for multiple objects on a page (using .class syntax most likely)
                // as long as each has a separate parent container. 
                return selector ? $el.parent().find(selector) : $el;
            }
        });
    };
}));



$(function() {
    //$("#top-left").css("height","100%");
});

$("#links").resizable({
    handleSelector: "#schiebeteil",
    resizeHeight: false,
    resizeWidthFrom: "right"
});

$("#rechts").resizable({
    handleSelector: "#schiebeteil",
    resizeHeight: false,
    resizeWidthFrom: "left"
});

$("#top-left").resizable({
    handleSelector: "#hori-drag",
    resizeWidth: false
});

$("#bottom-left").resizable({
    handleSelector: "#hori-drag",
    resizeWidth: false,
    resizeHeightFrom: "top"
});

$(".img-btn").on("click", function(e) {
    let fname = e.target.textContent;
    $("#main-image").attr("src", fname);
});

1 个答案:

答案 0 :(得分:0)

这是您解决500px断点的方法

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://necolas.github.io/normalize.css/8.0.1/normalize.css">
<link rel="stylesheet" href="style.css"/>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
</head>
<body>
<article id="links">At vero eos et accusam et justo duo dolores et ea rebum. 
Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit 
amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam 
nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed 
diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet 
clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit 
amet.
</article>
<div id="schiebeteil"></div>

<article id="rechts">

<section class="main-nav">
<div id="myBtnContainer">
<button class="btn active" onclick="filterSelection('all')">All works</button>
<button class="btn" onclick="filterSelection('illustrations')">Illustrations</button>
<button class="btn" onclick="filterSelection('animations')">Animations</button>
</div>
</section>

<section class="image-content">

<div class="column illustrations">
<div class="content">
<img src="https://www.uni-weimar.de/fileadmin/user/uni/hauptseiten/Startseite/Buehnenbanner/2019/04/csm_campusoffice_8e3bb1122c.jpg" >
<h4>Mountains</h4>
</div>
</div> 
 <div class="column illustrations">
  <div class="content">
   <img src="https://www.uni-weimar.de/fileadmin/user/uni/hauptseiten/Startseite/Buehnenbanner/2019/04/csm_campusoffice_8e3bb1122c.jpg" >
  <h4>Mountains</h4>
  </div>
  </div>
   <div class="column illustrations">
   <div class="content">
   <img src="https://www.uni-weimar.de/fileadmin/user/uni/hauptseiten/Startseite/Buehnenbanner/2019/04/csm_campusoffice_8e3bb1122c.jpg" >
  <h4>Mountains</h4>
  </div>
  </div> 
  <div class="column illustrations">
   <div class="content"><img src="https://www.uni-weimar.de/fileadmin/user/uni/hauptseiten/Startseite/Buehnenbanner/2019/04/csm_campusoffice_8e3bb1122c.jpg" >   
   <h4>Mountains</h4>
   </div>
   </div> 
   <div class="column animations">
   <div class="content">
   <img src="https://www.uni-weimar.de/fileadmin/user/uni/hauptseiten/Startseite/Buehnenbanner/2019/04/csm_campusoffice_8e3bb1122c.jpg" >
   <h4>Mountains</h4>
   </div>
   </div> 
   </section>

   </article>


   <script src="jsresize.js"></script>
   <script>
   filterSelection("all")
   function filterSelection(c) {
     var x, i;
     x = document.getElementsByClassName("column");
     if (c == "all") c = "";
     for (i = 0; i < x.length; i++) {
       w3RemoveClass(x[i], "show");
       if (x[i].className.indexOf(c) > -1) w3AddClass(x[i], "show");
     }
   }

   function w3AddClass(element, name) {
     var i, arr1, arr2;
     arr1 = element.className.split(" ");
     arr2 = name.split(" ");
     for (i = 0; i < arr2.length; i++) {
       if (arr1.indexOf(arr2[i]) == -1) {element.className += " " + arr2[i];}
     }
   }

   function w3RemoveClass(element, name) {
     var i, arr1, arr2;
     arr1 = element.className.split(" ");
     arr2 = name.split(" ");
     for (i = 0; i < arr2.length; i++) {
       while (arr1.indexOf(arr2[i]) > -1) {
         arr1.splice(arr1.indexOf(arr2[i]), 1);     
       }
     }
     element.className = arr1.join(" ");
   }


   // Add active class to the current button (highlight it)
   var btnContainer = document.getElementById("myBtnContainer");
   var btns = btnContainer.getElementsByClassName("btn");
   for (var i = 0; i < btns.length; i++) {
     btns[i].addEventListener("click", function(){
       var current = document.getElementsByClassName("active");
       current[0].className = current[0].className.replace(" active", "");
       this.className += " active";
     });
   }
   </script>

   </body>

   </html>

CSS:

    * {
    font-family: Arial;
    font-size: 40px;
    box-sizing: border-box;
    font-weight: normal;
    }

    body {
    height: 100%;
    display: flex;
    background-color: #eee;
    }

    #links,
    #rechts {
    width: 100%;
    height: 100vh;
    flex: 1 1 auto;
    flex-direction: column;
    min-width: 20%;
    overflow-y: auto;
    }

    #schiebeteil {
    width: 3px;
    flex: 0 0 auto;
    cursor: col-resize;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: black;
    }

    /* Create three equal columns that floats next to each other */
    .column {
    float: left;
    width: 50%;
    display: none; /* Hide all elements by default */
    }

    #rechts.smallSize .column {width:100%;}

    /* Content */
    .content {
    padding: 10px;
    }

    /* The "show" class is added to the filtered elements */
    .show {
    display: block;
    }

    #myBtnContainer {
    margin:0 auto;
    height:100%;   
    margin: 0px;
    padding: 0px;
    }

    /* Style the buttons */
    .btn {
    border: none;
    outline: none;
    cursor: pointer;
    background: none;
    color: black;
    padding: 0;
    margin: 0;
    line-height: 96%;
    font-size: 18px;
    margin-right:20px;
    float:right;
    height:100%;
    }

    .btn:hover {
    }

    .btn.active {
    }

    img {
    width: 100%;
    }

    h4 {
    font-size: 18px;
    padding: 0;
    margin: 0;
    }

    .image-content {
    float: left;
    margin-left: 48px;
    }

    .main-nav {
    width:100vh;    
    height:45px;
    position:fixed;
    -webkit-transform-origin: left top;
    -webkit-transform:rotate(-90deg) translateX(-100%);
    }

Js:

   /// <reference path="../bower_components/jquery/dist/jquery.js" />
   /*
   jquery-resizable
   Version 0.32 - 5/5/2018
   © 2015-2018 Rick Strahl, West Wind Technologies
   www.west-wind.com
   Licensed under MIT License
   */
   (function(factory, undefined) {
       if (typeof define === "function" && define.amd) {
    // AMD
    define(["jquery"], factory);
       } else if (typeof module === "object" && typeof module.exports === "object") {
    // CommonJS
    module.exports = factory(require("jquery"));
} else {
    // Global jQuery
    factory(jQuery);
}
   }(function($, undefined) {

       if ($.fn.resizable)
     return;

       $.fn.resizable = function fnResizable(options) {
           var defaultOptions = {
        // selector for handle that starts dragging
        handleSelector: null,
        // resize the width
        resizeWidth: true,
        // resize the height
        resizeHeight: true,
        // the side that the width resizing is relative to
        resizeWidthFrom: "right",
        // the side that the height resizing is relative to
        resizeHeightFrom: "bottom",
        // hook into start drag operation (event passed)
        onDragStart: null,
        // hook into stop drag operation (event passed)
        onDragEnd: null,
        // hook into each drag operation (event passed)
        onDrag: null,
        // disable touch-action on $handle
        // prevents browser level actions like forward back gestures
        touchActionNone: true,
        // instance id
        instanceId: null
       };
      if (typeof options == "object")
        defaultOptions = $.extend(defaultOptions, options);

      return this.each(function () {
        var opt = $.extend({}, defaultOptions);
        if (!opt.instanceId)
            opt.instanceId = "rsz_" + new Date().getTime();            

        var startPos, startTransition;

        // get the element to resize 
        var $el = $(this);
        var $handle;

        if (options === "destroy") {            
            opt = $el.data("resizable");
            if (!opt)
                return;

            $handle = getHandle(opt.handleSelector, $el);
            $handle.off("mousedown." + opt.instanceId + " touchstart." + opt.instanceId);
            if (opt.touchActionNone)
                $handle.css("touch-action", "");
            $el.removeClass("resizable");
            return;
        }

        $el.data("resizable", opt);

        // get the drag handle

        $handle = getHandle(opt.handleSelector, $el);

        if (opt.touchActionNone)
            $handle.css("touch-action", "none");

        $el.addClass("resizable");
        $handle.on("mousedown." + opt.instanceId + " touchstart." + opt.instanceId, startDragging);

        function noop(e) {
            e.stopPropagation();
            e.preventDefault();
        };

        function startDragging(e) {
            // Prevent dragging a ghost image in HTML5 / Firefox and maybe others    
            if ( e.preventDefault ) {
              e.preventDefault();
            }

            startPos = getMousePos(e);
            startPos.width = parseInt($el.width(), 10);
            startPos.height = parseInt($el.height(), 10);

            startTransition = $el.css("transition");
            $el.css("transition", "none");

            if (opt.onDragStart) {
                if (opt.onDragStart(e, $el, opt) === false)
                    return;
            }

            $(document).on("mousemove." + opt.instanceId, doDrag);
            $(document).on("mouseup." + opt.instanceId, stopDragging);
            if (window.Touch || navigator.maxTouchPoints) {
                $(document).on("touchmove." + opt.instanceId, doDrag);
                $(document).on("touchend." + opt.instanceId, stopDragging);
            }
            $(document).on("selectstart." + opt.instanceId, noop); // disable selection
            $("iframe").css("pointer-events","none");
        }

        function doDrag(e) {

            var pos = getMousePos(e), newWidth, newHeight;

            if (opt.resizeWidthFrom === "left")
                newWidth = startPos.width - pos.x + startPos.x;
            else
                newWidth = startPos.width + pos.x - startPos.x;

            if (opt.resizeHeightFrom === "top")
                newHeight = startPos.height - pos.y + startPos.y;
            else
                newHeight = startPos.height + pos.y - startPos.y;

            if (!opt.onDrag || opt.onDrag(e, $el, newWidth, newHeight, opt) !== false) {
                if (opt.resizeHeight)
                    $el.height(newHeight);                    

                if (opt.resizeWidth)
                    $el.width(newWidth);                    
            }
        }

        function stopDragging(e) {
            e.stopPropagation();
            e.preventDefault();

            $(document).off("mousemove." + opt.instanceId);
            $(document).off("mouseup." + opt.instanceId);

            if (window.Touch || navigator.maxTouchPoints) {
                $(document).off("touchmove." + opt.instanceId);
                $(document).off("touchend." + opt.instanceId);
            }
            $(document).off("selectstart." + opt.instanceId, noop);                

            // reset changed values
            $el.css("transition", startTransition);
            $("iframe").css("pointer-events","auto");

            if (opt.onDragEnd)
                opt.onDragEnd(e, $el, opt);

            return false;
        }

        function getMousePos(e) {
            var pos = { x: 0, y: 0, width: 0, height: 0 };
            if (typeof e.clientX === "number") {
                pos.x = e.clientX;
                pos.y = e.clientY;
            } else if (e.originalEvent.touches) {
                pos.x = e.originalEvent.touches[0].clientX;
                pos.y = e.originalEvent.touches[0].clientY;
            } else
                return null;

            return pos;
        }

        function getHandle(selector, $el) {
            if (selector && selector.trim()[0] === ">") {
                selector = selector.trim().replace(/^>\s*/, "");
                return $el.find(selector);
            }

            // Search for the selector, but only in the parent element to limit the scope
            // This works for multiple objects on a page (using .class syntax most likely)
            // as long as each has a separate parent container. 
            return selector ? $el.parent().find(selector) : $el;
        } 
    });
   };
 }));



   $(function() {
  //$("#top-left").css("height","100%");
   });

   $("#links").resizable({
      handleSelector: "#schiebeteil",
      resizeHeight: false,
      resizeWidthFrom: "right"
   });

   $("#rechts").resizable({
      handleSelector: "#schiebeteil",
      resizeHeight: false,
      resizeWidthFrom: "left",
     onDrag: function (e, $el, newWidth, newHeight, opt) {
     var elWidth = $el.width();
     if(elWidth < 500){
         $el.addClass('smallSize');
     }else{
         $el.removeClass('smallSize');
     }
     console.log($el.width());


   }
   });

   $("#top-left").resizable({
      handleSelector: "#hori-drag",
      resizeWidth: false
   });

   $("#bottom-left").resizable({
      handleSelector: "#hori-drag",
      resizeWidth: false,
     resizeHeightFrom: "top"
   });

   $(".img-btn").on("click", function(e) {
       let fname = e.target.textContent;
       $("#main-image").attr("src",fname);
   });

访问链接code