RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / user-386355

Владимир Говоров's questions

Martin Hope
Владимир Говоров
Asked: 2022-06-16 06:43:19 +0000 UTC

更改高度后获取元素的宽度

  • 0

我需要在元素被赋予高度后立即获得计算的宽度。

带有事件转换结束的变体。CSS 文件具有“过渡:高度 1 毫秒”。出于某种原因,getComputedStyle 有时会给出 0px

        const someElems = [elem1, elem2, elem3, elem4];
        let arrWidth: string[] = [];
        for (const element of someElems) {
            element.addEventListener("transitionend", () => arrWidth.push(window.getComputedStyle(element).width) );
            //после изменения высоты, обработчик события не запускается
            element.style.height = heightRow;
        }

未找到解决方案。仅适用于人为创建的延迟。getComputed 每次都返回正确的值。

        const someElems = [elem1, elem2, elem3, elem4];
        const height = "350px"
        let arrWidth: string[] = [];
        for (const element of someElems) {
            element.addEventListener("transitionend", () => arrWidth.push(window.getComputedStyle(element).width) );
            setTimeout(() => {
                element.style.height = height;
            }, 1000);
        }
javascript promise
  • 1 个回答
  • 47 Views
Martin Hope
Владимир Говоров
Asked: 2022-06-14 00:27:36 +0000 UTC

如何将一个对象的属性分配给另一个对象。具有相同类型的对象

  • 1

有 2 个具有相同类型的对象。一个对象(我们称之为“fulledObj”)最初被填充并遍历键。所有找到的属性都必须在迭代期间写入另一个对象(我们称之为“needfulProps”)。我必须马上说,将一个对象分配给另一个/克隆的解决方案是不合适的。我需要在 needfulProps 对象上覆盖/创建一个属性。

* 非工作部分在代码中标有注释:

                    type responsiveArguments = {
                        heightRow?: string,
                        widthColumn?: string,
                        countColumns?: number,
                        countRows?: number,
                        rowGap?: number
                    }
                    let needfulResponsiveProps: responsiveArguments = {};
                    let oneWidthResponsiveObj: responsiveArguments = {
                        heightRow: "300px",
                        widthColumn: "500px",
                        countRows: 2
                    }
                    for (const keyResponsiveObj of Object.keys(oneWidthResponsiveObj) as (keyof responsiveArguments)[]) {
                        // Вывести в консоль объект с этим свойством я могу
                        console.log(`needfulResponsiveProps[keyResponsiveObj]: `,  needfulResponsiveProps[keyResponsiveObj]);
                        // Присвоить не могу
                        // Тип "string | number | undefined" не может быть назначен для типа "undefined". Тип "string" не может быть назначен для типа "undefined"
                        needfulResponsiveProps[keyResponsiveObj] = oneWidthResponsiveObj[keyResponsiveObj];
                    }

此外,如果对象类型中的所有字段都属于同一类型,则一切正常:

                    type exampleType = { //все поля одного типа(number)
                        num?: number,
                        num2?: number
                    }

                    const filledObj: exampleType = {
                        num: 10,
                        num2: 15
                    }
                    let testConst: exampleType = {};
                    for (const key of Object.keys(filledObj) as (keyof exampleType)[]) {
                        testConst[key] = filledObj[key];
                    }

完整的代码,从中可以清楚为什么简单的对象复制是不合适的:

type responsive = {
            [resolution: number]: responsiveArguments;
        }
        type responsiveArguments = {
            heightRow?: string | undefined;
            widthColumn?: string | undefined;
            countColumns?: number | undefined;
            countRows?: number | undefined;
            rowGap?: number | undefined;
        }        
        /* for test */viewWidthDevice = 1500; // ширина устройства - будет считаться автоматически
        /* for test */responsive = {
            500: {
                countColumns: 500,
                countRows: 2
            },
            800: {
                countRows: 50,
                heightRow: "500px"
            },
            1900: {
                countColumns: 50
            }
        }
        
        let objPropsLessWidth: responsive = {};
        if(responsive) {
            for(let i = 0; i < viewWidthDevice; i++) {
                if(responsive.hasOwnProperty(i)) {
                    objPropsLessWidth[i] = responsive[i];
                };
            }
            console.log("objPropsLessWidth: ", objPropsLessWidth); //ключ 1900 будет убран, ведь ширин

            if(Object.keys(objPropsLessWidth).length > 0) {
                let needfulResponsiveProps: responsiveArguments = {};

                for (const keyOneResponsiveWidth in objPropsLessWidth) { // enumeration all responsive appropriate properties  
                    const oneWidthResponsiveObj: responsiveArguments = objPropsLessWidth[keyOneResponsiveWidth];
                    
                    //надо так:
                    for (const keyResponsiveObj of Object.keys(oneWidthResponsiveObj) as (keyof responsiveArguments)[]) {
                        //в левом операнде ошибка
                        //Тип "string | number | undefined" не может быть назначен для типа "undefined". Тип "string" не может быть назначен для типа "undefined".
                        needfulResponsiveProps[keyResponsiveObj] = oneWidthResponsiveObj[keyResponsiveObj];
                    }

                    //хочу избавиться от этого промежутка кода в сторону цикла, который выше
                    if(oneWidthResponsiveObj.countColumns) needfulResponsiveProps.countColumns = oneWidthResponsiveObj.countColumns;
                    if(oneWidthResponsiveObj.countRows) needfulResponsiveProps.countRows = oneWidthResponsiveObj.countRows;
                    if(oneWidthResponsiveObj.heightRow) needfulResponsiveProps.heightRow = oneWidthResponsiveObj.heightRow;
                    if(oneWidthResponsiveObj.rowGap) needfulResponsiveProps.rowGap = oneWidthResponsiveObj.rowGap;
                    if(oneWidthResponsiveObj.widthColumn) needfulResponsiveProps.widthColumn = oneWidthResponsiveObj.widthColumn;
                }
            }
        }
typescript
  • 1 个回答
  • 10 Views
Martin Hope
Владимир Говоров
Asked: 2022-06-12 21:41:24 +0000 UTC

在循环中访问可选对象属性

  • 1

我有一个可以选择接收某些属性的数组。您如何使用循环访问它们中的每一个?我正在编写一个插件,它具有响应属性,可以动态适应不同的设备。埃斯林特向我发出了这个警告:

const exampleObj: responsiveProps 该元素隐式属于“any”类型,因为“string”类型的表达式不能用于索引“responsiveProps”类型。在类型参数“string”的“responsiveProps”类型中找不到索引签名

                    type responsiveProps = {
                        heightRow?: string,
                        widthColumn?: string,
                        countColumns?: number,
                        countRows?: number,
                        rowGap?: number
                    }

                    const exampleObj: responsiveProps = {
                        heightRow: "300px",
                        countRows: 3
                    }
                    
                    for (const key in exampleObj) {
                        if (Object.prototype.hasOwnProperty.call(exampleObj, key) 
                         && exampleObj.hasOwnProperty(key)) {
                            // здесь exampleObj[key] будет выбивать вышеупомянутое предупреждение 
                            const responsiveProp = exampleObj[key];
                            console.log(responsiveProp)
                        }
                    }

                    //получается сделать только так:
                    if(exampleObj.countColumns)
                        /* действие */
                        console.log(exampleObj.countColumns);
                    if(exampleObj.countRows)
                        /* действие */
                        console.log(exampleObj.countRows)

这是另一个尝试:

                    for (let i = 0; i < Object.keys(exampleObj).length; i++) {
                        const nameProperty: string = Object.keys(exampleObj)[i];

                        if(exampleObj.hasOwnProperty(nameProperty)) {
                            //да, здесь снова предупреждение
                            console.log(exampleObj[nameProperty]);
                        }
                    }

在我看来,成功的机会更大。尽管打字稿绝对不在乎礼貌,对谁以及看起来如何

问题的附录:

                    const exampleObj: responsiveProps = {
                        heightRow: "300px",
                        countRows: 3
                    }
                    const needfulResponsiveProps: responsiveProps = {};

                    for (const key of Object.keys(exampleObj) as (keyof responsiveProps)[]) {
                        //Тип "string | number | undefined" не может быть назначен для типа "undefined".
  Тип "string" не может быть назначен для типа "undefined"
                        needfulResponsiveProps[key] = exampleObj[key]
                    }
javascript
  • 1 个回答
  • 10 Views
Martin Hope
Владимир Говоров
Asked: 2022-08-29 03:37:35 +0000 UTC

如何访问php文件?

  • 0

React 中有一个应用程序。有必要将表单中的数据发送到电子邮件。我不知道如何正确访问 php.ini 中已经准备好的文件。在控制台中使用 Ajax 时不断出现错误“POST ...sitename/mail.php 405”

如何正确访问php文件?我把它放在公共场所和文件本身旁边。

.php 文件:

    <?php
    $method = $_SERVER['REQUEST_METHOD'];
    $c = true;
    if ( $method === 'POST' ) {

    $project_name = trim($_POST["project_name"]);
    $admin_email  = trim($_POST["admin_email"]);
    $form_subject = trim($_POST["form_subject"]);
    
    foreach ( $_POST as $key => $value ) {
        if ( $value != "" && $key != "project_name" && $key != "admin_email" && $key != "form_subject" ) {
            $message .= "
            " . ( ($c = !$c) ? '<tr>':'<tr style="background-color: #f8f8f8;">' ) . "
                <td style='padding: 10px; border: #e9e9e9 1px solid;'><b>$key</b></td>
                <td style='padding: 10px; border: #e9e9e9 1px solid;'>$value</td>
            </tr>
            ";
        }
    }
    } else if ( $method === 'GET' ) {

    $project_name = trim($_GET["project_name"]);
    $admin_email  = trim($_GET["admin_email"]);
    $form_subject = trim($_GET["form_subject"]);

    foreach ( $_GET as $key => $value ) {
        if ( $value != "" && $key != "project_name" && $key != "admin_email" && $key != "form_subject" ) {
            $message .= "
            " . ( ($c = !$c) ? '<tr>':'<tr style="background-color: #f8f8f8;">' ) . "
                <td style='padding: 10px; border: #e9e9e9 1px solid;'><b>$key</b></td>
                <td style='padding: 10px; border: #e9e9e9 1px solid;'>$value</td>
            </tr>
            ";
        }
    }
    }

    $message = "<table style='width: 100%;'>$message</table>";

    function adopt($text) {
    return '=?UTF-8?B?'.Base64_encode($text).'?=';
    }

    $headers = "MIME-Version: 1.0" . PHP_EOL .
    "Content-Type: text/html; charset=utf-8" . PHP_EOL .
    'From: '.adopt($project_name).' <'.$admin_email.'>' . PHP_EOL .
    'Reply-To: '.$admin_email.'' . PHP_EOL;

    mail($admin_email, adopt($form_subject), $message, $headers );
    }

用表单反应元素:

    class FeedbackForm extends Component {
    componentDidMount() {
        if(FeedbackForm.defaultProps.prefferedLinkMethod !== this.props.prefferedLinkMethod)
            this.setState({prefferedLinkMethod: this.props.prefferedLinkMethod})

        //E-mail Ajax Send
        $("form").submit(function() { //Change
            console.log(this); //delete

            var th = $(this);
            $.ajax({
                type: "POST",
                url: "mail.php", //Change
                data: th.serialize()
            }).done(function(response) {
                console.log("response: ", response)
                alert("Thank you!");
                setTimeout(function() {
                    // Done Functions
                    th.trigger("reset");
                }, 1000);
            }).catch((error) => {
                console.log("Something went wrong with Ajax", error)
            });

            return false;
        });
    }

    render() {
        return(
            <form>
                {/* Hidden Required Fields*/}
                <input type="hidden" name="project_name" value="name site" />
                <input type="hidden" name="admin_email" value="email@email.com" />
                <input type="hidden" name="form_subject" value="where form" />
                {/* <!-- END Hidden Required Fields --> */}

                <input type="text" name="name" />
                <input type="text" name="telephone" />
                <input type="text" name="email"  />
                <button >Отправить</button>
            </form>
        )
    }
    }
php
  • 1 个回答
  • 10 Views
Martin Hope
Владимир Говоров
Asked: 2022-10-09 07:08:38 +0000 UTC

将鼠标悬停在子元素中的文本上时,“onmouseover”事件停止工作。怎么修?

  • 1

有一个用 addEventListener() 声明的 mouseover 事件。将鼠标悬停在所需对象上后,附加标记将作为子元素嵌入到同一对象中。但是,当将鼠标悬停在这些新创建的子元素(图像和文本)上时,事件将停止工作。如何解决?在新标记出现的地方,我在 JS 代码中留下了单行注释。

    <section class="about-us">
        <div class="container">
            <div class="title">What we do</div>
            <div class="subtitle">Story about us</div>
            <div class="divider"></div>
            <div class="desciption">
                Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
            </div>
            <div class="about-us__wrapper-images">
                <div class="about-us__wrapper-for-hover">
                    <div class="about-us__wrapper-bgImage">
                        <img src="icons/about-us_block/USERS.png" alt="users picture" alt="" class="about-us__hover-image-team">
                        <div class="about-us__hover-text">super team</div>
                        <!-- background image -->
                    </div>
                </div>
                <div class="about-us__wrapper-for-hover">
                    <div class="about-us__wrapper-bgImage">
                        <!-- background image -->
                    </div>
                </div>
                <div class="about-us__wrapper-for-hover">
                    <div class="about-us__wrapper-bgImage">
                        <!-- background image -->
                    </div>
                </div>
            </div>
        </div>
    </section>
const wrapperImages = document.querySelectorAll(".about-us__wrapper-for-hover"),
      imgAtPage = document.querySelectorAll(".about-us__wrapper-bgImage"),
      obfUrlImages = [`url("img/about-us/1.jpg")`, 
                      `url("img/about-us/2.jpg")`,
                      `url("img/about-us/3.jpg")`
                     ];
 
imgAtPage.forEach( (img, i) => {
    img.style.cssText += `
        background-image: ${obfUrlImages[i]};
    `;
});
 
wrapperImages.forEach( (wrapperImgs, i) => {
    wrapperImgs.addEventListener("mouseover", () => {
        wrapperImgs.style.cssText = `
            background-color: #95e1d3;
        `;
 
        const wrapperImg = wrapperImgs.querySelector(".about-us__wrapper-bgImage");
        wrapperImg.style.cssText += `
            transform: translate(-10px, -10px);
            background-image: linear-gradient(to top, rgba(252, 227, 138, 0.9) 0%, rgba(243, 129, 129, 0.9) 100%),
                                ${obfUrlImages[i]};
        `;
        wrapperImg.innerHTML = ` //эти картинка и текст после появления мешают работе события
        <img src="icons/about-us_block/USERS.png" alt="users picture" alt="happy users picture" class="about-us__hover-image-team">
            <div class="about-us__hover-text">super team</div>
        `;
    });
    wrapperImgs.addEventListener("mouseout", () => {
        wrapperImgs.style.cssText = ``;
 
        const wrapperImg = wrapperImgs.querySelector(".about-us__wrapper-bgImage");
        wrapperImg.style.removeProperty("transform");
        wrapperImg.style.cssText += `
            background-image: ${obfUrlImages[i]};
        `;
        wrapperImg.innerHTML = "";
    });
});

此屏幕上有 3 张图片。 第一个被鼠标悬停并且“mouseover”事件处于活动状态。 相应地,如果用户将鼠标移到新出现的用户图片或文字上,就会中断。

javascript
  • 1 个回答
  • 10 Views
Martin Hope
Владимир Говоров
Asked: 2020-05-18 23:37:28 +0000 UTC

是否可以由用户主动创建类的新实例,如果“是”,那么如何实现呢?那么,如果“不”,那么如何躲闪呢?

  • 1

程序逻辑:程序循环工作——这样做是为了让鱼“变老”。在循环的每次迭代中,用户可以将其中一条鱼拉出水族箱,也可以将一条新鱼添加到水族箱中(问题由此产生)。根据我的想法,应该如何实现添加:用户输入鱼种(例如,Ancistrus)。这种特殊品种的新鱼正在被创造出来。(问题出现了——毕竟,有必要创建一个类的实例(一条新鱼),为此,有必要提前做这一切,但这只是对计算机的亵渎资源。那么如何制作它以便在用户的命令下创建一条鱼?)
代码中第一个突出显示的片段是一个函数,用户可以使用它向水族箱添加另一条鱼(在循环中完成 -> 可以重复多次)。然后有一个我无能为力的问题:用户想要添加鱼->您需要创建该类的另一个实例(当然具有唯一的名称)。
在以粗体突出显示的第二个片段中,向您展示了“AddFish()”函数本身,它还引用了一个名称相似的函数,但已经来自 Aquarium 类 - 该函数仅扩展数组并引入新的鳞片一个在那里。第二个突出显示的片段是问题。(不能用用户刚刚在命令行输入的名称来实例化一个类. 我可以随机命名类的新实例,但我认为这是不可能的。)事实上,要做什么,如何解决这个问题???
对于这个问题,我只想出了一个解决方案——提前创建许多类的实例(可以将它们保留为“null”值),当用户想要向水族箱添加某种鱼时,如果你愿意,想要的鱼会“变得活跃”、“从睡眠中醒来”……

'''c#
        static void Main(string[] args)
        {
            int whatToDo;
            string info;
            Random random = new Random();

            Ancistrus ancistrus = new Ancistrus();
            Astronotus astronotus = new Astronotus();
            Barbus barbus = new Barbus();
            Guppy guppy = new Guppy(); //Все вышеперечисленные пользовательские 
//классы наследованы от Fish.

            Fish[] fishes = new Fish[] { ancistrus, astronotus, barbus, guppy };

            Aquarium aquarium = new Aquarium(fishes); //В аквариум добавляются рыбы.


            while (true)
            {   
                Console.WriteLine("Аквариум запущен. Команды для взаимодействия:\n" +
                                  "1 - продолжение жизни;\n" +
                                  "2 - добавить в аквариум рыбу;\n" +
                                  "3 - вытащить из аквариума рыбу;\n");

                info = aquarium.GetInfo(); 
                Console.WriteLine(info); //Выводит информацию о рыбах в аквариуме.

                AgingAll(aquarium._fishes); //Здесь рыбы стареют на 1 год.

                Int32.TryParse(Console.ReadKey().ToString(), out whatToDo);
                switch(whatToDo) //2 - добавить рыбу, 3 - вытащить рыбу,
    // любая другая клавиша - продолжить выполнение программы(рыбы просто постареют).
                {
                    case 2:
                        **AddFish(aquarium);** //добавление рыбы в аквариум. 
                        break;
                    case 3:
                        //RemoveFish();
                        break;
                    default:
                        break;
                }

                Console.Clear();
            }
        }

static void AddFish(Aquarium aquarium)
    {
        Console.Write("Рыбу с каким именем вы хотите добавить?  ");
        string nameNewFish = Console.ReadLine();

        if (nameNewFish == Ancistrus.Breed) //Если имя, введенное пользователем аналогично породе Ancistrus, то...
            **Ancistrus nameNewFish = new Ancistrus();** //проблема - как создать новый экземпляр

        aquarium.AddFish(nameNewFish); //уже созданная рыба добавляется в аквариум.
    }
'''
c#
  • 1 个回答
  • 10 Views

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5